我有示例集合:
db.books.find()
{ "author" : "Coetzee", "is_favourite" : true, "version" : 1 }
{ "author" : "Coetzee", "is_favourite" : true, "version" : 1 }
{ "author" : "Coetzee", "is_favourite" : false, "version" : 2 }
{ "author" : "King", "is_favourite" : false, "version" : 2 }
{ "author" : "Cohen", "is_favourite" : true, "version" : 2 }
{ "author" : "Cohen", "is_favourite" : false, "version" : 3 }
{ "author" : "Picasso", "is_favourite" : true, "version" : 3 }
通过运行:
db.books.aggregate([
{ $match: {"is_favourite":{ $ne: true}}},
{ $group: { _id: "$author"}}
])
我得到以下内容:
{ "_id" : "Cohen" }
{ "_id" : "King" }
{ "_id" : "Coetzee" }
我该怎么办才能只获得符合"is_favourte": false
的对象?
在这个特殊情况下,我只想获得"author": "King"
答案 0 :(得分:1)
假设您希望作者is_favourite始终为false,您可以使用:
db.books.aggregate([
{
$group:{
_id:"$author",
is_fav:{
$push:"$is_favourite"
}
}
},
{
$match:{
is_fav:{
$nin:[
true
]
}
}
},
{
$project:{
_id:1
}
}
],{
allowDiskUse: true
})
返回
{ "_id" : "King" }