Home > Net >  Should i aggregate to merge two collection?
Should i aggregate to merge two collection?

Time:12-22

I am a newbie in MongoDB and NoSQL, I am doing a simple app with 2 collection tasks_list and user, the structure like this

tasks_list

{
    "_id" : ObjectId("61c03dfb47370c024193afde"),
    "name" : "complete unit 2",
    "createBy" : ObjectId("61c03f6b47370c024193afe0")
}

users

{
    "_id" : ObjectId("61c03f6b47370c024193afe0"),
    "name" : "admin",
    "image" : "img_default.jpg"
}

I want to get the document of task_list, so I think I should be call find() 2 collection tasks_list, users or using aggregate to join collection and use find() in tasks_list. What is the right way?

CodePudding user response:

You can use aggregate() query:

db.tasks_list.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "createBy",
      "foreignField": "_id",
      "as": "createBy"
    }
  },
  {
    "$set": {
      "createBy": {
        "$first": "$createBy"
      }
    }
  }
])

Working example

If you are using Mongoose, you can use populate() method:

TaskLists.find().populate('createBy');
  • Related