gpt4 book ai didi

javascript - MongoDB - 即时从 ID 获取数据

转载 作者:搜寻专家 更新时间:2023-10-30 23:28:56 24 4
gpt4 key购买 nike

我有这个示例数据

帖子

[{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: 'Foo'
},
{
_id: ObjectId("507f191e810c19729de860ea"),
name: 'Bar'
},
{
_id: ObjectId("5b8797747ea41163b7eb51b0"),
name: 'FooBar'
}]

类别

[{
_id: ObjectId("5b87979c10397d6c12d69513"),
name: 'Funny',
type: 1
},
{
_id: ObjectId("5b8797ab24098febfb05abdd"),
name: 'Sad',
type: 1
},
{
_id: ObjectId("5b8797b24e31ebf7603f3c3e"),
name: 'Romantic',
type: 2
}]

最后一个是关系

[{
_id: ObjectId("5b879818763ecd6f1c54d306"),
postID: ObjectId("507f1f77bcf86cd799439011"),
categoryID: ObjectId("5b87979c10397d6c12d69513")
},
{
_id: ObjectId("5b8798eb040890fb2a88c0af"),
postID: ObjectId("507f1f77bcf86cd799439011"),
categoryID: ObjectId("5b8797b24e31ebf7603f3c3e"),
}]

当我在 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"),
}]
}

在这种情况下,这是我在关系中的所有示例数据,无论如何如何只获取类别数据而不是关系数据,我想得到这样的东西:

{
_id: ObjectId("507f1f77bcf86cd799439011"),
name: 'Foo',
categories: [{
_id: ObjectId("5b87979c10397d6c12d69513"),
name: 'Funny',
type: 1
},
{
_id: ObjectId("5b8797b24e31ebf7603f3c3e"),
name: 'Romantic',
type: 2
}]
}

最佳答案

您可以尝试从 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"
}}
])

关于javascript - MongoDB - 即时从 ID 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52091410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com