node.js - 使用 $lookup 比较两个字段的查询

标签 node.js mongodb mongodb-query aggregation-framework

用户集合

[   
    {name: "alex", age: 25, surname: "brown"},
    {name: "tom", age: 34, surname: "gray"},
    {name: "alex", age: 65, surname: "red"},
    {name: "alex", age: 32, surname: "yellow"}
]

参与征集

[   
    {name: "alex", age: 32}
]

我只想获取一份名为 alex 且年龄为 32 的文档的详细信息。

到目前为止我做了什么?

db.participation.aggregate([
   {$lookup: "users" , foreignField: "name" , localField: "name", as: "document"},
   {$unwind: "document"},
   {$match: {age: "$document.age"}}
])

但是这没有返回任何内容,返回的数组是空的。

那么我应该如何创建查询?

最佳答案

执行此操作的最佳方法是在 MongoDB 3.4 中使用 $replaceRoot 管道运算符来 reshape 文档。另外,您不应该在此处使用 $unwind

[
   { "$match": { "name":"alex", "age": 32 } },
   {
      "$lookup": {
         "from": "user",
         "foreignField": "name",
         "localField": "name",
         "as": "result"
      }
   },
   {
      "$replaceRoot" :{
         "newRoot": {
            "$arrayElemAt": [
               {
                  "$filter": {
                     "input": "$result",
                     "cond": {
                        "$and": [
                            { "$eq": [ "$$this.age", 32 ] },
                            { "$eq": [ "$$this.name", "alex" ] }
                        ]
                     }
                  }
               },
               0
            ]
         }
      }
   }
]

关于node.js - 使用 $lookup 比较两个字段的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762488/

相关文章:

node.js - twitter request_token 端点总是返回 "couldn' t 验证你”

javascript - streams2 Writable - 有没有办法定义 "_end"函数?

python - Pandas - 将数据框插入 MongoDB

mongodb - 如何在 MongoDB 2.6 副本集上启用 HTTP 控制台

javascript - 仅当值较大时才更新 mongo 文档

MongoDB 插入 key 为 '$'(美元)

mongodb - 是否有用于基于字段过滤所有嵌套/子文档的 Mongo 函数?

javascript - 如何扩展nodejs url 模块中的URL 类以向其中添加属性?

javascript - 在node.js中的elasticsearch中创建空索引

mongodb - 使用另一个字段的值更新 MongoDB 字段