mongodb - 查找聚合中的局部变量不起作用

标签 mongodb mongodb-query aggregate

我有两个集合,callcontact

我想加入他们并在通话记录中显示联系人姓名。下面的代码是我尝试过的。

ps。当我将 "d.v":"$mobile" 更改为 "d.v":"some number" 时它可以工作,但是当我使用变量时不起作用,我的问题在哪里?

{
  from: 'contact',
  let: {"mobile":"$user"},
  pipeline:[
    {
        "$project":{
          d:{$objectToArray:"$data"},
          doc:"$$ROOT",
        }
    },
    {
        "$unwind":{
          path: "$d",
          preserveNullAndEmptyArrays: true
        }
    },
    {
        "$match":{
          "d.v":"$mobile"
          }
    },
],
  as: 'name'
}

最佳答案

docs 中所述:

To reference variables in pipeline stages, use the "$$" syntax.

...

A $match stage requires the use of an $expr operator to access the variables. The $expr operator allows the use of aggregation expressions inside of the $match syntax.

更改这两项以满足要求后,您的舞台将如下所示:

db.call.aggregate([
  {
    "$lookup": {
      from: "contact",
      let: {
        "mobile": "$user"
      },
      pipeline: [
        {
          "$project": {
            d: {
              $objectToArray: "$data"
            },
            doc: "$$ROOT",
            
          }
        },
        {
          "$unwind": {
            path: "$d",
            preserveNullAndEmptyArrays: true
          }
        },
        {
          "$match": {
            $expr: {
              $eq: [
                "$$mobile",
                "$d.v"
              ]
            }
          }
        },
        
      ],
      as: "name"
    }
  }
])

Mongo Playground

关于mongodb - 查找聚合中的局部变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69243241/

相关文章:

iphone - NSPredicate 聚合函数 [SIZE] 给出 'unsupported function expression' 错误

node.js - MongoDB:推送到嵌套数组或更新现有数组元素

PHP - 比较两个 mongodate

sql - 在 SQL 中求值的情况

java - MongoDB java API 聚合 $lookup 和管道使用变量

node.js - 如何更新 Mongoose 中的特定字段?

python - 保存引用字段 mongoengine

mysql - 存储版本控制的数据库数据的标准/推荐方法是什么?

mongoDB,求和两个字段的乘积

mongodb - 如何检查一个集合中 _id 的一部分是否出现在另一个集合中