如何只获得符合mongodb标准的对象?

时间:2016-11-03 19:47:27

标签: mongodb mongodb-query

我有示例集合:

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"

1 个答案:

答案 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" }