Mongo 查询 - 匹配和查找相结合

Mongo Query - match and lookup combined

我定义了以下查询,它为我获取了给定 ids 列表中带有 id 且状态为 active 或 [=] 的所有项目18=].

const query = { 
   $and : [ 
     { 
       $or: [
         { 
           status: ‘active’,
         }, 
         { 
           status: ‘retracted’,
         },
       ], 
     }, 
     {
        id: { $in: ids }, 
     }, 
  ],
};

这些项目中的每一个都有一个 parent_id 字段,如果该项目没有父项,则该字段可以是 null,也可以是父项的 ID。

我希望我的查询能够获取我提供的 ids 的所有项目,以及它们的父项(如果存在这样的父项)。

例如,如果我提供以下 ID

[1,2,3]

并且项目 2 的父级 ID 为 5,而项目 1 和项目 3 的 parent_id 设置为 null,我希望我的查询 return 以下项目:

[1,2,3,5].

为了实现这一点,我编写了以下查询:

const collection = db.collection(‘myCollection’);

const data = await collection.aggregate([ 
      {$match : query}, 
      {
        $lookup: { 
          from: ‘myCollection’, 
          let: { parentID: ‘$parent_id’}, 
          pipeline: [ 
             { 
                $match: { 
                  $expr: { 
                    $eq: [‘$id’, ‘$$parentID’], 
                  }, 
                }, 
             }, 
          as: ‘parent’, 
         }, 
      }, 
     ]).sort(‘created_date’, ‘desc’).toArray();

return data; 

但是,这总是 return 为空。

示例数据:

[
{
id: 1, 
parent_id: 3, 
data: ‘bla bla’
}, 
{
id: 2, 
parent_id: null, 
data: ‘bla bla bla’
},
{
id: 3, 
parent_id: null, 
data: ‘bla’
}
]

输入:[1]

输出:

[
{
id: 1, 
parent_id: 3, 
data: ‘bla bla’
}, 
{
id: 3, 
parent_id: null, 
data: ‘bla’
}
]

您的聚合格式不正确并且缺少一些“]”,例如关闭管道字段。

如果你修复了查询对我来说工作正常。 Example

$lookup 在同一个集合上 运行 的方法应该有效,但是它为您提供了一个嵌套数组,因此您需要几个额外的阶段来展平这样的数组并获取结果集中的所有元素:

db.collection.aggregate([
    {
        $match: { id: { $in: [1] } }
    },
    {
        $lookup: {
            from: "collection",
            localField: "parent_id",
            foreignField: "id",
            as: "parent"
        }
    },
    {
        $project: {
            all: {
                $concatArrays: [
                    "$parent",
                    [ "$$ROOT" ]
                ]
            }
        }
    },
    {
        $project: {
            "all.parent": 0
        }
    },
    {
        $unwind: "$all"
    },
    {
        $replaceRoot: {
            newRoot: "$all"
        }
    }
])

Mongo Playground

你可以试试这个。输入数组是 [2,3] ,其中 2 的父 id=1 并且不在输入数组中。但是输出数组有条目。

工作Playground

db.collection.aggregate([
  {
    $match: {
      _id: {
        $in: [
          2,
          3
        ]
      }
    }
  },
  {
    $lookup: {
      from: "collection",
      localField: "p",
      foreignField: "_id",
      as: "parent"
    }
  },
  {
    $project: {
      _id: 0,
      id: {
        $concatArrays: [
          [
            "$_id"
          ],
          "$parent._id"
        ]
      }
    }
  },
  {
    $unwind: "$id"
  },
  {
    $sort: {
      id: 1
    }
  }
])