如何在mogodb中的嵌入式文档字段上使用$ lookup

时间:2016-09-22 13:15:25

标签: node.js mongodb aggregation-framework mean-stack mongoose-schema

请看一下,您的帮助将会得到满足

var user = new Schema({
      name: String,

    });

var Comments = new Schema({
    title     : String
  , body      : String
  ,user_id :  {type: Schema.Types.ObjectId, ref: 'user' }
  , date      : Date

});


var blog = new Schema({
    author    : String
  , title     : String
  , body      : String
  , date      : Date
  , user_id   :{type: Schema.Types.ObjectId, ref: 'user' }
  , comments  : [Comments]

});



db.blogs.aggregate([
    { $match : { "_id" : ObjectId("57e3b7f4409d80a508d52769") } },

{ $lookup: {from: "users", localField: "user_id", foreignField: "_id", as: "User"} },

])

返回

[
  {
    "_id": "57e3b7f4409d80a508d52769",
    "author": "Tariq",
    "title": "MyfirstPost",
    "body": "This is my first post",
    "user_id": "57e3b763f7bc810c08f9467a",
    "comments": [
      {
        "title": "hi",
        "body": "again i am commenting on this",
        "user_id": "57e3b763f7bc810c08f9467a",
        "_id": "57e3c153409d80a508d5276b"
      },
      {
        "title": "hi",
        "body": "this is seond comment",
        "user_id": "57e3b763f7bc810c08f9467a",
        "_id": "57e3c8632ebca0ee0afb2ac6"
      }
    ],
    "__v": 0,
    "User": [
      {
        "_id": "57e3b763f7bc810c08f9467a",
        "name": "Tariq",
        "username": "teekay",
        "password": "123456",
        "__v": 0
      }
    ]
  }
]

这个返回结果通过比较博客表是和用户表_id这很好..但是我想通过使用“comments.user_id”博客集合的user_id和集合的“_id”得到每个评论的用户详细信息 应该是这样的

"_id": "57e3b7f4409d80a508d52769",
    "author": "Tariq",
    "title": "MyfirstPost",
    "body": "This is my first post",
    "user_id": "57e3b763f7bc810c08f9467a",
    "comments": [
      {
        "title": "hi",
        "body": "again i am commenting on this",
        "user_id": "57e3b763f7bc810c08f9467a",
        "_id": "57e3c153409d80a508d5276b",
  "User": [
      {
        "_id": "57e3b763f7bc810c08f9467a",
        "name": "Tariq",
        "username": "teekay",
        "password": "123456",
        "__v": 0
      }
    ]
      },

1 个答案:

答案 0 :(得分:1)

您可以运行管道的聚合操作:

db.blogs.aggregate([
    { "$unwind": "$comments" },
    { 
        "$lookup": {
            "from": "users", 
            "localField": "comments.user_id", 
            "foreignField": "_id", 
            "as": "comments.user"
        } 
    },
    { "$unwind": "$comments.user" },
    {
        "$group": {
            "_id": "$_id",
            "author": { "$first": "$author" },
            "title": { "$first": "$title" },
            "body": { "$first": "$body" },
            "comments": { "$push": "$comments" },
            "user_id": { "$first": "$user_id" }
        }
    },
    { 
        "$lookup": {
            "from": "users", 
            "localField": "user_id", 
            "foreignField": "_id", 
            "as": "user"
        } 
    },
    { "$unwind": "$user" },
])