【发布时间】:2019-10-04 07:27:24
【问题描述】:
我一直在 stackoverflow 上搜索,但找不到我正在寻找的确切内容,希望有人能提供帮助。我想根据该文档的数组提交单个查询,为单个文档返回多个计数。
我的数据:
db.myCollection.InsertOne({
"_id": "1",
"age": 30,
"items": [
{
"id": "1",
"isSuccessful": true,
"name": null
},{
"id": "2",
"isSuccessful": true,
"name": null
},{
"id": "3",
"isSuccessful": true,
"name": "Bob"
},{
"id": "4",
"isSuccessful": null,
"name": "Todd"
}
]
});
db.myCollection.InsertOne({
"_id": "2",
"age": 22,
"items": [
{
"id": "6",
"isSuccessful": true,
"name": "Jeff"
}
]
});
我需要返回的是文档以及与所述文档的 items 数组关联的计数。在此示例中,文档 _id = "1":
{
"_id": "1",
"age": 30,
{
"totalIsSuccessful" : 2,
"totalNotIsSuccessful": 1,
"totalSuccessfulNull": 1,
"totalNameNull": 2
}
}
我发现我可以使用下面类似的方法在 4 个查询中得到这个,但我真的希望它是一个查询。
db.test1.aggregate([
{ $match : { _id : "1" } },
{ "$project": {
"total": {
"$size": {
"$filter": {
"input": "$items",
"cond": { "$eq": [ "$$this.isSuccessful", true ] }
}
}
}
}}
])
提前致谢。
【问题讨论】:
标签: mongodb mongodb-query