简体   繁体   中英

MongoDB multiple joins with sub documents

I have two collections,

Users collection:

{
    "userId": 1,
    "name": 'John',
    "profile": 'john.png'
},
{
    "userId": 2,
    "name": 'Doe',
    "profile": 'doe.png'
},
{
    "userId": 3,
    "name": 'John Doe',
    "profile": 'johndoe.png'
}

Posts collection:

{
    "postId": 1,
    "userId": 1,
    "postContent": "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
    "comments": [
        {
            "comment": "sample comment",
            "commentedBy": 2,
        },
        {
            "comment": "Another sample comment",
            "commentedBy": 3,
        }
    ],
}

How can I get post details including individual post's user details & individual comment's user details with a single query in mongoose?

you may want to use the "populate" method provided by Mongoose: https://mongoosejs.com/docs/populate.html

It allow you to "link" your collections in the schema definition, and query & populate all related collections in a single query, something like

Posts.findOne({ postId: 1 }).populate('user')

Follow the documentation link above for further details on how to write your Schemas.

You can use $aggregate and $lookup to perform such

db.posts.aggregate(
  [
    {
      $lookup:
      {
        from: "users",
        localField: "userId",
        foreignField: "userId",
        as: "users"
      }
    }
  ]
).pretty()

This will print as below

{
        "_id" : ObjectId("5ecceb468d4390391825b79d"),
        "postId" : 1,
        "userId" : 1,
        "postContent" : "Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
        "comments" : [
                {
                        "comment" : "sample comment",
                        "commentedBy" : 2
                },
                {
                        "comment" : "Another sample comment",
                        "commentedBy" : 3
                }
        ],
        "users" : [
                {
                        "_id" : ObjectId("5ecceb168d4390391825b79a"),
                        "userId" : 1,
                        "name" : "John",
                        "profile" : "john.png"
                }
        ]
}

Reference from MongoDB

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM