簡體   English   中英

Mongo Query - 匹配和查找相結合

[英]Mongo Query - match and lookup combined

我定義了以下查詢,該查詢獲取給定ids列表中具有id所有項目,並且狀態為activeretracted

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 ,我希望我的查詢返回以下項目:

[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; 

但是,這始終返回 null。

樣本數據:

[
{
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’
}
]

您的聚合格式不正確並且缺少一些“]”,例如關閉管道。

如果您修復該查詢對我來說工作正常。 例子

在同一個集合上運行$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"
        }
    }
])

蒙戈游樂場

你可以試試這個。 輸入數組是[2,3] ,其中 2 的父 id=1 並且不在輸入數組中。 但是輸出數組有條目。

工作游樂場

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
    }
  }
])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM