检索不包含具有布尔值的字段的文档

时间:2017-08-03 21:09:36

标签: mongodb mongodb-query aggregation-framework

假设我们有一个包含如下数据的集合:

{
   "_id":"4313e7aa192d75b7c3cffc8af0312fdeb",
   "name":"Foo",
   "services":[
      {
         "serviceID":"378e7aa192d75b7c3cffc8aq033fdeb",
         "isActive":true
      },
      {
         "serviceID":"5403e7aa192d75b7c3cffc8af033fdex",
         "isActive":false
      },
      {
         "serviceID":"e918e7aa192d75b7c3cffc8ax0233fdey",
         "isActive":true
      }
   ]
},
{
   "_id":"b1d8b857963e35521faef87d215ca3f7",
   "name":"Foo",
   "services":[
      {
         "serviceID":"b98857963e35521faef87d215ca3f8",
         "isActive":false
      }
   ]
},
{
   "_id":"34efdb9e62c2131e050917b4524d6e6f",
   "name":"Foo",
   "services":[
      {
         "serviceID":"39efba9e62c2131e050917b4524d6e6f",
         "isActive":false
      },
      {
         "serviceID":"34ex1b9e62c2131e050917b4524d6e6x",
         "isActive":false
      }
   ]
}

现在,我们如何查询检索没有任何活动服务的文档(我的意思是不包含"isActive":true的文档)?这样的查询是否有运算符?

任何想法都会受到赞赏......

3 个答案:

答案 0 :(得分:0)

如此简单的事情:

collection.find( { "services.isActive": { $ne: true } } )

答案 1 :(得分:0)

如果在结果文档中您不介意在服务数组中看到 isActive = true ,那么@dnickless写的就足够了。

如果你介意的话,试试这个:

db.collection.aggregate([
{
    $unwind: "$services"
},
{
    $match: {
      "services.isActive": false 
    }
}
])

答案 2 :(得分:0)

According to description as mentioned in above question please try executing following aggregate query into MongoDB shell

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: "$services"
        },

        // Stage 2
        {
            $match: {
            $or:[
            {'services.isActive':{$exists:false}},
            {'services.isActive':false}

            ]
            }
        },

    ]



);

The above mentioned aggregate query executes multiple stages of aggregation pipeline

$unwind operator splits an array into separate documents for each element of array.

$match operator filters documents consisting of key isActive with value false or either isActive key does not exist into document from returned result set through execution of $unwind stage.