在Mongo DB中查询带有条件的子元素的数量 [英] Query the count of sub elements with condition in Mongo DB
问题描述
我是Mongo DB的新手,并希望在以下查询任务中获得一些帮助.
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"
}
}
我正在尝试查询,以便我为集合中的每个元素(1)确切指定要返回的字段(在这种情况下为subfield_1
和subfield_2
,而(2)仅用于subfield_1
返回true
个元素的计数.所以我希望输出看起来像这样:
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"
}
}
我一直在尝试这段代码,但这只给了我subfield_1
中每个元素的条目数:
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'}
}
}
)
提前谢谢!
推荐答案
您需要运行 $ objectToArray 将嵌套的构造函数转换为键和值的数组,然后使用 $ filter 仅获取true
值:
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 DB中查询带有条件的子元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!