问题
I am new to Mongo DB and would appreciate some help with the following query task.
I have a collection of documents that looks like below:
{
"field_1" : {
"subfield_1" : {
"subsubfield_1" : "true",
"subsubfield_2" : "false",
"subsubfield_3" : "true"
},
"subfield_2" : "sf2"
},
"field_2" : {
"subfield_1" : {
"subsubfield_1" : "true",
"subsubfield_2" : "false"
},
"subfield_2" : "sf2"
},
"field_3" : {
"subfield_1" : {
"subsubfield_1" : "true",
"subsubfield_2" : "false",
"subsubfield_3" : "false"
},
"subfield_2" : "sf2"
}
}
And I am trying to query such that I, for each element in the collection (1) specify exactly which fields to return (in this case subfield_1
and subfield_2
, and, (2) for subfield_1
only return the count of true
elements. So I would like the output to look like:
{
{
"subfield_1" : 2,
"subfield_2" : "sf2"
},
{
"subfield_1" : 1,
"subfield_2" : "sf2"
},
{
"subfield_1" : 1,
"subfield_2" : "sf2"
}
}
I have been trying this code but that only gives me the number of entries in subfield_1
for each element:
db.getCollection('myCollection').aggregate(
{
$match: {<some other condition>}
},
{
$project: {
subfield_2: 1,
subfield_1: {'$size': '$subfield_1'}
}
}
)
Thanks in advance!
回答1:
You need to run $objectToArray to transform your nested structer into an array of keys and values and then use $unwind to get a separate document for every sub-document. Then you can run another $objectToArray
along with $filter to get only true
values:
db.collection.aggregate([
{
$project: {
doc: { $objectToArray: "$$ROOT" }
}
},
{
$unwind: "$doc"
},
{
$match: { $expr: { $ne: [ "$doc.k", "_id" ] } }
},
{
$project: {
_id: 0,
subfield_1: { $size: { $filter: { input: { $objectToArray: "$doc.v.subfield_1" }, cond: { $eq: [ "$$this.v", "true" ] } } } },
subfield_2: "$doc.v.subfield_2"
}
}
])
Mongo Playground
来源:https://stackoverflow.com/questions/59719488/query-the-count-of-sub-elements-with-condition-in-mongo-db