[英]MongoDB - get data from ID on the fly
I have this sample data我有这个样本数据
Posts帖子
[{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: 'Foo'
},
{
_id: ObjectId("507f191e810c19729de860ea"),
name: 'Bar'
},
{
_id: ObjectId("5b8797747ea41163b7eb51b0"),
name: 'FooBar'
}]
Categories类别
[{
_id: ObjectId("5b87979c10397d6c12d69513"),
name: 'Funny',
type: 1
},
{
_id: ObjectId("5b8797ab24098febfb05abdd"),
name: 'Sad',
type: 1
},
{
_id: ObjectId("5b8797b24e31ebf7603f3c3e"),
name: 'Romantic',
type: 2
}]
And the last one is relationships最后一个是关系
[{
_id: ObjectId("5b879818763ecd6f1c54d306"),
postID: ObjectId("507f1f77bcf86cd799439011"),
categoryID: ObjectId("5b87979c10397d6c12d69513")
},
{
_id: ObjectId("5b8798eb040890fb2a88c0af"),
postID: ObjectId("507f1f77bcf86cd799439011"),
categoryID: ObjectId("5b8797b24e31ebf7603f3c3e"),
}]
When I use a $lookup in Mongo I get something like this:当我在 Mongo 中使用 $lookup 时,我得到如下信息:
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: 'Foo',
categories: [{
_id: ObjectId("5b879818763ecd6f1c54d306"),
postID: ObjectId("507f1f77bcf86cd799439011"),
categoryID: ObjectId("5b87979c10397d6c12d69513")
},
{
_id: ObjectId("5b8798eb040890fb2a88c0af"),
postID: ObjectId("507f1f77bcf86cd799439011"),
categoryID: ObjectId("5b8797b24e31ebf7603f3c3e"),
}]
}
In this case, this is my all example data in relationships, anyway how to get just categories data instead of relationships data, I want to get something like this:在这种情况下,这是我在关系中的所有示例数据,无论如何如何仅获取类别数据而不是关系数据,我想获得如下内容:
{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: 'Foo',
categories: [{
_id: ObjectId("5b87979c10397d6c12d69513"),
name: 'Funny',
type: 1
},
{
_id: ObjectId("5b8797b24e31ebf7603f3c3e"),
name: 'Romantic',
type: 2
}]
}
You can try below aggregation from mongodb 3.6您可以从 mongodb 3.6尝试以下聚合
db.collection.aggregate([
{ "$match": { "_id": ObjectId("507f1f77bcf86cd799439011") } },
{ "$lookup": {
"from": "Relationship",
"let": { "categoryID": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$categoryID", "$$categoryID" ] } } },
{ "$lookup": {
"from": "Category",
"let": { "categoryID": "$categoryID" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$categoryID" ] } } }
],
"as": "category"
}},
{ "$unwind": "$category" },
{ "$replaceRoot": { "newRoot": "$category" }}
],
"as": "categories"
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.