[英]How to query subdocuments using $lookup in mongodb?
I have a personal project and I am new in MongoDB aggregate function.我有一个个人项目,我是 MongoDB 聚合函数的新手。 I got the correct result querying two collections using
$lookup
but I want to modify the result and get my desired output.我使用
$lookup
查询两个集合得到了正确的结果,但我想修改结果并获得我想要的输出。
Here is my Sample Collection这是我的样本集
"users": [
{
"_id" : "60499e72b60a8819c4e0fa03"
"LastName": "Doe"
"FirstName" "John"
}
]
"userdocuments": [
{
"_id": "61025b9f890bacbe8f450f6a",
"userid": 60499e72b60a8819c4e0fa03,
documents: {
documentOne: {
documentTitle: "This is Document One"
},
documentTwo: {
documentTitle: "This is Document Two"
},
documentThree: {
documentTitle: "This is Document Three"
},
}
}
]
I'm getting a correct result like this using $lookup
and $unwind
https://mongoplayground.net/p/k1lmvJg-tB7我使用
$lookup
和$unwind
https://mongoplayground.net/p/k1lmvJg-tB7得到了这样的正确结果
[
{
"FirstName": "John",
"LastName": "Doe",
"_id": "60499e72b60a8819c4e0fa03",
"documents": {
"_id": "61025b9f890bacbe8f450f6a",
"userid": "60499e72b60a8819c4e0fa03"
"documents": {
"documentOne": {
"documentTitle": "This is Document One"
},
"documentThree": {
"documentTitle": "This is Document Three"
},
"documentTwo": {
"documentTitle": "This is Document Two"
}
},
}
}
]
But I want my output like this.但我希望我的输出是这样的。 And I want to project
userid
and _id
so I can get my desired output.我想投影
userid
和_id
以便我可以得到我想要的输出。 Thanks you so much for helping非常感谢你的帮助
[
{
"FirstName": "John",
"LastName": "Doe",
"_id": "60499e72b60a8819c4e0fa03",
"documents": {
"documentOne": {
"documentTitle": "This is Document One"
},
"documentThree": {
"documentTitle": "This is Document Three"
},
"documentTwo": {
"documentTitle": "This is Document Two"
}
},
}
}
]
You can select first element from documents
array by $arrayElemAt
or $first
(v4.4) operators after lookup stage,您可以在查找阶段后通过
$arrayElemAt
或$first
( $arrayElemAt
) 运算符从documents
数组中选择第一个元素,
{
$addFields: {
Documents: {
$arrayElemAt: ["$Documents.documents", 0]
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.