如果将松散应用于猫鼬中使用聚合时不存在的字段会发生什么 [英] What will happen if unwind is applied to a field which is not present while using aggregation in mongoose

查看:82
本文介绍了如果将松散应用于猫鼬中使用聚合时不存在的字段会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在字段上使用 $ unwind 在猫鼬模式中
根据以上链接,如果不存在该字段,则展开将忽略输入文档
我该如何防止这种情况,即使不存在该字段即不忽略输入文档,也无需取消处理即可返回查询结果

Lets say I am using a $unwind on a field in mongoose schema
According to the above link If field is not present then unwind will ignore input document
How can I prevent that so that result of query is returned without unwinding process even if field is not present i.e input document is not ignored

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  

推荐答案

根据上面的链接,如果不存在该字段,则展开将引发错误

According to the above link If field is not present then unwind will throw an error

不,不是:

  • 如果由字段路径指定的字段中的值是不是数组,则db.collection.aggregate()会生成错误.
  • 如果您为输入文档中不存在的字段指定了路径,则管道将忽略,并且不会为该输入文档输出文档.
  • If a value in the field specified by the field path is not an array, db.collection.aggregate() generates an error.
  • If you specify a path for a field that does not exist in an input document, the pipeline ignores the input document and will not output documents for that input document.

这是一个简单的例子:

> 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"""


根据您的编辑,如果需要保留带有 missing 字段的文档以展开,则可以使用


As per your edit, if you need to keep documents with a missing field to unwind, you can $project a default value using $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 }

这篇关于如果将松散应用于猫鼬中使用聚合时不存在的字段会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆