我是mongoDb的新手。我已经设置了两个收藏品。( 1)第2卷)评论
book :
_id
title
author
posted
price评论意见是:
_id
bookId
comment
status我想得到那些有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."});
});
});当我打电话给我的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": []
}
]
}我需要有状态1值的评论的数据。我尝试过在$match之后使用$lookup,但它不起作用。我也尝试过使用$eq,这也不适合我。可能是因为我刚刚开始学习mongodb,所以我把它设置得很错误。
发布于 2018-09-28 07:27:52
您可以在这里使用$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] }
}
}
}}
])发布于 2018-09-28 07:59:16
从MongoDB v3.6.3开始,最快的查询性能将实现如下所示:
确保在bookId集合中的status字段和comments集合中有一个索引:
db.comments.createIndex({ "bookId": 1, "status": 1 })然后使用$lookup stage (文档)的新的文档属性:
db.books.aggregate([{
"$lookup": {
"from": "comments",
"let": { "bId": "$_id" },
"pipeline": [{
"$match": {
$expr: { $eq: [ "$bookId", "$$bId" ] },
"status": 1
}
}],
"as": "comments"
}
}])https://stackoverflow.com/questions/52550354
复制相似问题