这是mongodb Playground中的代码。
我有一个查询,如下所示:
db.posts.aggregate({
$lookup: {
from: "users",
let: {comments: "$comments"},
pipeline: [
{$match: {$expr: {$in: ["$_id", "$$comments.userId"]} }},
{"$addFields":{"text": "$$comments.text"}}
],
as: "comments"
}
})
此查询的问题在于,text
我得到的值是一个包含来自all的文本的数组comments
。如果我尝试按过滤userId
,则会遇到另一个问题。如果用户评论不止一次,则该text
值将是一个包含其所有的数组comments
。
如何获得一个对象中的查找用户及其评论?
编辑
我期望结果如下所示:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"id": "1",
"comments": [
{
"_id": "u1",
"name": "James",
"username": "jamo",
"text": "Hi there, who are you?"
},
{
"_id": "u1",
"name": "James",
"username": "jamo",
"text": "Hi! Are you still there?"
}
],
}
]
$unwind
解构comments
数组$lookup
加入用户集合,$unwind
得到...的对象 user
$group
通过_id
并comments
用必填字段进行重构db.posts.aggregate([
{ $unwind: "$comments" },
{
$lookup: {
from: "users",
localField: "comments.userId",
foreignField: "_id",
as: "comments.user"
}
},
{ $unwind: "$comments.user" },
{
$group: {
_id: "$_id",
id: { $first: "$id" },
comments: {
$push: {
_id: "$comments._id",
text: "$comments.text",
username: "$comments.user.username",
name: "$comments.user.name"
}
}
}
}
])
第二种选择,不带$unwind
,
$lookup
与users
收藏$map
迭代comments
数组循环$filter
迭代users
数组的外观并找到匹配的用户信息$arrayElemAt
从$ filter返回已过滤用户的第一个对象$mergeObjects
将合并评论对象和用户信息db.posts.aggregate([
{
$lookup: {
from: "users",
localField: "comments.userId",
foreignField: "_id",
as: "users"
}
},
{
$project: {
comments: {
$map: {
input: "$comments",
as: "c",
in: {
$mergeObjects: [
"$$c",
{
$arrayElemAt: [
{
$filter: {
input: "$users",
cond: { $eq: ["$$c.userId", "$$this._id"] }
}
},
0
]
}
]
}
}
}
}
}
])
我尚未测试两个查询的性能,请尝试并使用合适的查询
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句