MongoDB多计数、单文档、数组
我一直在stackoverflow上搜索,无法准确找到我要找的内容,希望有人能帮助我。我想根据一个文档的数组,为一个文档提交一个查询,返回多个计数 我的数据:MongoDB多计数、单文档、数组,mongodb,mongodb-query,Mongodb,Mongodb Query,我一直在stackoverflow上搜索,无法准确找到我要找的内容,希望有人能帮助我。我想根据一个文档的数组,为一个文档提交一个查询,返回多个计数 我的数据: db.myCollection.InsertOne({ "_id": "1", "age": 30, "items": [ { "id": "1", "isSuccessful": true, "name": null },{ "id": "2", "
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”:
我发现我可以用下面这样的方法在4个查询中得到它,但我真的希望它是一个查询
db.test1.aggregate([
{ $match : { _id : "1" } },
{ "$project": {
"total": {
"$size": {
"$filter": {
"input": "$items",
"cond": { "$eq": [ "$$this.isSuccessful", true ] }
}
}
}
}}
])
谢谢。
< P>我假设你的预期结果是无效的,因为你在另一个对象的中间有一个对象文字,而且你有<代码>完全成功的< /代码> <代码> ID:1 < /代码>作为代码> 2 < /代码>,看起来它们应该是<代码> 3 < /代码>。话虽如此 您可以通过$unwind
获得类似的输出,然后使用$sum
和$cond
进行分组:
db.collection.aggregate([
{ $match: { _id: "1" } },
{ $unwind: "$items" },
{ $group: {
_id: "_id",
age: { $first: "$age" },
totalIsSuccessful: { $sum: { $cond: [{ "$eq": [ "$items.isSuccessful", true ] }, 1, 0 ] } },
totalNotIsSuccessful: { $sum: { $cond: [{ "$ne": [ "$items.isSuccessful", true ] }, 1, 0 ] } },
totalSuccessfulNull: { $sum: { $cond: [{ "$eq": [ "$items.isSuccessful", null ] }, 1, 0 ] } },
totalNameNull: { $sum: { $cond: [ { "$eq": [ "$items.name", null ]}, 1, 0] } } }
}
])
输出结果如下:
[
{
"_id": "_id",
"age": 30,
"totalIsSuccessful": 3,
"totalNameNull": 2,
"totalNotIsSuccessful": 1,
"totalSuccessfulNull": 1
}
]
您可以可能重复的
[
{
"_id": "_id",
"age": 30,
"totalIsSuccessful": 3,
"totalNameNull": 2,
"totalNotIsSuccessful": 1,
"totalSuccessfulNull": 1
}
]