node.js - 如果 unwind 应用于在 mongoose 中使用聚合时不存在的字段,将会发生什么

标签 node.js mongodb mongoose

假设我正在使用 $unwind在 Mongoose 模式中的字段上
根据上面的链接,如果字段不存在,则 unwind 将忽略输入文档
我怎样才能防止这种情况发生,即使字段不存在,即不忽略输入文档,也不会在没有展开过程的情况下返回查询结果

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

不,它不会:

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

根据您的编辑,如果您需要保留一个缺少字段的文档以展开,您可以$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 }

关于node.js - 如果 unwind 应用于在 mongoose 中使用聚合时不存在的字段,将会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687607/

相关文章:

ruby - 命令 'grunt server' 的 compass 错误

javascript - FeatherJS 和 SwaggerUI : Could not resolve pointer:/definitions/messages

javascript - Node 加载例程完成后,来自 mongodb 集合的文档 "disappearing"

mongodb - 在同一台主机的两个不同容器上运行 MongoDB 和 Redis

node.js - NodeJS、Mongoose - findOneAndUpdate 无法从服务器工作

javascript - 如何等待 mongoose .exec 函数完成?

date - 如何使用 Node.js 和 Mongoose 查询日期?

node.js - 如何在 Node.js 10 中从缓冲区读取/写入 bigint?

mongodb - 如何在 Apache Airflow 中连接到 Mongodb?

mongodb - 如何在 mongodb 配置文件中设置授权?