![](/img/trans.png)
[英]MongoDB updating all records in a collection with the results of query from another collection
[英]MongoDB - Find all the records from another table
我有以下两个表:
注释 :
{
"createdOn": "2020-03-08T04:19:20.276Z",
"comment": "First comment in the app",
"likesCount": 1,
"_id": "5e6472c32fe18a59b1068f46",
"userId": "5e60ec371dc3d30e61c6805b",
"postId": "5e6356546d284c2cdfe1ad92",
"__v": 0
}
评论喜欢:
{
"createdOn": "2020-03-08T06:47:58.855Z",
"_id": "5e64955abb6056610f802159",
"userId": "5e60ec371dc3d30e61c6805b",
"commentId": "5e6472c32fe18a59b1068f46",
"__v": 0
}
现在我试图通过以下查询获得所有喜欢:-
Comments.aggregate([
{$match: {postId : postId}},
{$lookup:{
from: 'commentLikes',
localField: '_id',
foreignField: 'commentId',
as : 'likes'
}}
])
.exec()
它没有返回任何喜欢。 我从这个查询中得到的回应是:-
{
"_id": "5e6472c32fe18a59b1068f46",
"createdOn": "2020-03-08T04:19:20.276Z",
"comment": "First comment in the app",
"likesCount": 1,
"userId": "5e60ec371dc3d30e61c6805b",
"postId": "5e6356546d284c2cdfe1ad92",
"__v": 0,
"likes": []
}
不知道我在这里做错了什么。 请帮忙。
当每个人都说查询可以,问题应该出在集合名称上时。 然后我尝试使用以下代码获取我的收藏列表:-
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
//trying to get collection names
mongoose.connection.db.listCollections().toArray(function (err, names) {
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
});})
我很惊讶猫鼬将所有系列的名称改为小写字母。 集合名称commentLikes变成了commentlikes 。 现在我的查询运行良好。
如果comments 集合中_id
字段的类型是ObjectId()
类型&如果commentLikes 集合中的commentId
是字符串,则尝试以下查询:
Comments.aggregate([
{ $match: { postId: postId } },
{
$lookup:
{
from: "commentLikes",
let: { id: { $toString: "$_id" } }, // Convert ObjectId() to string to match with type of commentId(string)
pipeline: [
{
$match:
{
$expr:
{ $eq: ["$$id", "$commentId"] }
}
}
],
as: "likes"
}
}
])
.exec()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.