可以说我在猫鼬模式的字段上使用$ unwind
根据上面的链接如果不存在field,那么unwind会忽略输入文档。
如何防止这种情况,以便即使不使用field也不返回过程也不返回查询结果存在,即输入文档不被忽略
if a particular field exists
I want to do unwind and some more stuff (project and group)
else
I want input document no changes in this case
根据以上链接,如果不存在该字段,则展开将引发错误
不,它不会:
- 如果由字段路径指定的字段中的值不是数组,则db.collection.aggregate()会生成错误。
- 如果您为输入文档中不存在的字段指定路径,则管道将忽略输入文档,并且不会输出该输入文档的文档。
这是一个简单的示例:
> db.test.insert({a:[1]})
> db.test.insert({})
> db.test.aggregate({$unwind:'$a'})
{ "_id" : ObjectId("557362a17b97d77c38793c21"), "a" : 1 }
// no error -- but unwind only the document having the `a` field.
但:
> db.test.insert({a:2})
> db.test.aggregate({$unwind:'$a'})
// will result in error 15978:
// """Value at end of $unwind field path '$a' must be an Array,
// but is a NumberDouble"""
根据您的修改,如果需要保留缺少字段的文档以展开,则可以$project
使用$ifNull
以下默认值:
> db.test.find()
{ "_id" : ObjectId("557362a17b97d77c38793c21"), "a" : [ 1 ] }
{ "_id" : ObjectId("557362a57b97d77c38793c22") }
> db.test.aggregate([
{$project: { a: { $ifNull: ['$a', [ null ]]}}},
{$unwind: "$a"}
])
{ "_id" : ObjectId("557362a17b97d77c38793c21"), "a" : 1 }
{ "_id" : ObjectId("557362a57b97d77c38793c22"), "a" : null }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句