MongoDB管道展开并检查空数组



我正在展开一个字段,它是一个日期对象数组,但是在某些情况下,有空数组很好。我想要使用管道进行相同的处理,但在某些情况下,我想过滤具有空数组的结果。

pipeline = []
pipeline.append({"$unwind": "$date_object"})
pipeline.append({"$sort": {"date_object" : 1}}) 

我想使用管道格式,但是以下代码不返回任何记录:

pipeline.append({"$match": {"date_object": {'$exists': False }}})

以下方法也不起作用:

pipeline.append({"$match": {"date_object": []}})

然后:

results = mongo.db.xxxx.aggregate(pipeline)

我也在尝试:

pipeline.append({ "$cond" : [ { "$eq" : [ "$date_object", [] ] }, [ { '$value' : 0 } ], '$date_object' ] } )

但是有了这个,我得到以下错误:

.$cmd failed: exception: Unrecognized pipeline stage name: '$cond'

但是,如果我使用查找(例如 find({"date_object": []}))进行查询,则可以获得这些结果。我怎样才能在管道中做到这一点。

我已经在MongoDB shell中做过了,但它可以很容易地翻译成Python语言。

这是您的要求吗?

我想你有这样的结构:

db.collection.save({foo:1, date_object:[new Date(), new Date(2016,1,01,1,0,0,0)]})
db.collection.save({foo:2, date_object:[new Date(2016,0,16,1,0,0,0),new Date(2016,0,5,1,0,0,0)]})
db.collection.save({foo:3, date_object:[]})
db.collection.save({foo:4, date_object:[new Date(2016,1,05,1,0,0,0), new Date(2016,1,06,1,0,0,0)]})
db.collection.save({foo:5, date_object:[]})
// Get empty arrays after unwind
db.collection.aggregate([
    {$project:{_id:"$_id", foo:"$foo", 
        date_object:{
            $cond: [ {"$eq": [{ $size:"$date_object" }, 0]}, [null], "$date_object" ]
        }
      }
    },
    {$unwind:"$date_object"},
    {$match:{"date_object":null}}
])
// Get empty arrays before unwind
db.collection.aggregate([
    {$match:{"date_object.1":{$exists:false}}},
    {$project:{_id:"$_id", foo:"$foo", 
        date_object:{
            $cond: [ {"$eq": [{ $size:"$date_object" }, 0]}, [null], "$date_object" ]
        }
      }
    },
    {$unwind:"$date_object"}
])

只有空的date_object

[ 
    {
        "_id" : ObjectId("56eb0bd618d4d09d4b51087a"),
        "foo" : 3,
        "date_object" : null
    }, 
    {
        "_id" : ObjectId("56eb0bd618d4d09d4b51087c"),
        "foo" : 5,
        "date_object" : null
    }
]

最后,如果你只需要空date_object,你不需要聚合,你可以用find轻松实现它:

db.collection.find({"date_object.1":{$exists:false}},{date_object:0})

输出

{
    "_id" : ObjectId("56eb0bd618d4d09d4b51087a"),
    "foo" : 3
}
{
    "_id" : ObjectId("56eb0bd618d4d09d4b51087c"),
    "foo" : 5
}

最新更新