簡體   English   中英

Mongo db查詢以過濾文檔中的嵌套對象數組

[英]Mongo db Query to filter nested array of objects in document

我有以下文件

{
    "userid": "5a88389c9108bf1c48a1a6a7",
    "email": "abc@gmail.com",
    "lastName": "abc",
    "firstName": "xyz",
    "__v": 0,
    "friends": [{
        "userid": "5a88398b9108bf1c48a1a6a9",
        "ftype": "SR",
        "status": "ACCEPT",
        "_id": ObjectId("5a9585b401ef0033cc8850c7")
    },
    {
        "userid": "5a88398b9108bf1c48a1a6a91111",
        "ftype": "SR",
        "status": "ACCEPT",
        "_id": ObjectId("5a9585b401ef0033cc8850c71111")
    },
    {
        "userid": "5a8ae0a20df6c13dd81256e0",
        "ftype": "SR",
        "status": "pending",
        "_id": ObjectId("5a9641fbbc9ef809b0f7cb4e")
    }]
},
{
    "userid": "5a88398b9108bf1c48a1a6a9",
    "friends": [{ }],
    "lastName": "123",
    "firstName": "xyz",
    .......
},
{
    "userid": "5a88398b9108bf1c48a1a6a91111",
    "friends": [{ }],
    "lastName": "456",
    "firstName": "xyz",
    ...
}   
  • 第一次查詢

在這里,我想從好友數組中獲取用戶 ID,其狀態等於“接受”。 IE

 [5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111] 
  • 第二次查詢

之后,我必須對同一個集合進行另一個查詢,以獲取第一個查詢中返回的每個用戶 ID 的詳細信息。 最終查詢將返回[5a88398b9108bf1c48a1a6a9,5a88398b9108bf1c48a1a6a91111]詳細信息,這兩個用戶 ID 即

[
        {
         userid" : "5a88398b9108bf1c48a1a6a9",
         "lastName" : "123",
         "firstName" : "xyz"
         },
       {
         "userid" : "5a88398b9108bf1c48a1a6a91111",
          "lastName" : "456",
           "firstName" : "xyz"
       }
   ]

到目前為止我已經嘗試過

 Users.find ({'_id':5a88389c9108bf1c48a1a6a7,"friends.status":'ACCEPT'}, (error, users) => {})  
   or 


 Users.find ({'_id':5a88389c9108bf1c48a1a6a7, friends: { $elemMatch: { status: 'ACCEPT' } } }, (error, users) => {})

使用聚合框架的$map$filter運算符來處理任務。 $filter將根據狀態應該等於"ACCESS"的指定條件過濾friends數組, $map會將過濾后的數組的結果轉換為所需的格式。

對於第二個查詢,附加$lookup管道步驟,該步驟在users集合上執行自聯接,以檢索與先前管道中的id匹配的文檔。

運行以下聚合操作將生成所需的數組:

User.aggregate([
    { "$match": { "friends.status": "ACCEPT" } },
    { "$project": {
            "users": {
                "$map": {
                    "input": {
                        "$filter": {
                            "input": "$friends",
                            "as": "el",
                            "cond": { "$eq": ["$$el.status", "ACCEPT"] }
                        }
                    },
                    "as": "item",
                    "in": "$$item.userid"
                }
            }
    } },
    { "$lookup": {  
        "from": "users",
        "as": "users",
        "localField": "users",
        "foreignField": "userid"
    } },
]).exec((err, results) => {
    if (err) throw err;
    console.log(results[0].users); 
});

我沒有測試它。 只是為了一個想法,試一試讓我知道。

 db.Users.aggregate(
       [
        {
           $unwind: "$friends"
        },
        {
          $match:{ "$friends.status": "ACCEPT"}
        },
        {
        $project:{ "FriendUserID":"$friends.userid"}
        },
        { 
          $lookup:{  
             from:"Users",
             as: "FriendsUsers",
             localField: "FriendUserID",
             foreignField: "userid"
          }
        },
        {
          $project: { FriendsUsers.lastName:1,FriendsUsers.firstName:1 }
        }
       ]
    )

過濾嵌套元素

const products = await Product.aggregate<ProductDoc>([
    {
      $match: {
        userId: data.id,
      },
    },
    {
      $project: {
        promotions: {
          $filter: {
            input: '$promotions',
            as: 'p',
            cond: {
              $eq: ['$$p.status', PromotionStatus.Started],
            },
          },
        },
        userId: 1,
        name: 1,
        thumbnail: 1,
      },
    },
  ]);

暫無
暫無

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

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