MongoDB-即时从ID获取数据

时间:2018-08-30 07:27:08

标签: javascript database mongodb aggregation-framework backend

我有这个样本数据

帖子

[{
 _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
   }]
}

1 个答案:

答案 0 :(得分:1)

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