在 mongodb 中的 $lookup 中应用条件

khu*_*boo 5 mongodb aggregation-framework

我是 mongoDb 的新手。我已经设置了两个集合。1) 书 2) 评论

book : 
_id
title
author
posted
price
Run Code Online (Sandbox Code Playgroud)

和评论是:

_id
bookId
comment
status
Run Code Online (Sandbox Code Playgroud)

我想得到那些书的评论status = 1

我试过这个。

return new promise((resolve, reject) => {
    db.collection('book').aggregate([
        {
            $lookup:{
                from:'comments',
                localField: "_id",
                foreignField: "bookId",
                as: "comments"                                                                  
            }
        }      
    ]).toArray().then((result) => {
        if(result.length > 0){
            res.send({ status: 1, message: "Success.", data:result });
        }else{
            res.send({ status: 0, message: "No data found." });
        }
    }).catch((err) => {
        res.send({ status: 0, message: "Something went wrong."});
    });
});
Run Code Online (Sandbox Code Playgroud)

当我调用我的 API 时,我在邮递员那里得到了这个。

{
"status": 1,
"message": "Success.",
"data": [
    {
        "_id": "5bacad201bff841afb40791f",
        "title": "Game of thrones",
        "author": "John snow",
        "posted": "16/07/1995",
        "price": 1000,
        "comments": [
            {
                "_id": "5bacc31aa2d365256cab31ce",
                "bookId": "5bacad201bff841afb40791f",
                "comment": "Winter is comming"
            },
            {
                "_id": "5bacc3f65c716925df953615",
                "bookId": "5bacad201bff841afb40791f",
                "comment": "It has a level of politics"
            },
            {
                "_id": "5bacd60ea38cc526f1fee1d1",
                "bookId": "5bacad201bff841afb40791f",
                "comment": "It has a level of politics",
                "status": 1
            }
        ]
    },
    {
        "_id": "5bacad601bff841afb407920",
        "title": "Breaking bed",
        "author": "Haison burg",
        "posted": "20/08/2002",
        "price": 550,
        "comments": []
    }
]
}
Run Code Online (Sandbox Code Playgroud)

我需要评论具有状态 1 值的数据。我试过$match之后使用,$lookup但它不起作用。我也尝试使用$eq这对我也不起作用。由于我刚刚开始学习 mongodb,我可能以错误的方式设置它。

Ash*_*shh 3

您可以在此处使用$addFields$filter聚合

db.collection("book").aggregate([
  { "$lookup": {
    "from": "comments",
    "localField": "_id",
    "foreignField": "bookId",
    "as": "comments"                                                                  
  }},
  { "$addFields": {
    "comments": {
      "$filter": {
        "input": "$comments",
        "cond": { "$eq": ["$$this.status", 1] }
      }
    }
  }}
])
Run Code Online (Sandbox Code Playgroud)