Search code examples
node.jsmongodbreferencemongodb-querydereference

How can I query on a referenced field in MongoDB?


I have two collections, users and posts. The relevant parts of a typical document looks like this:

user

{
   "_id": "user1",
   "name": "Joe",
   "age": 20
}

posts

{
   "content": "Yo what's up!",
   "created": "2018-02-05T05:00:00.000Z",
   "author": "user1"
}

I would like to create a query on the posts collection that returns the following:

{
       "content": "Yo what's up!",
       "created": "2018-02-05T05:00:00.000Z",
       "author": {
            "name": "Joe",
            "age": 20
}

Is there any way to do this in raw MongoDB? I'm using the MongoDB Node.js client.


Solution

  • Using aggregation with lookup operator.

    db.posts.aggregate([
    {"$lookup":{
        "from":"users",
        "localField":"author",
        "foreignField":"_id",
        "as":"author"
    }},
    {"$addFields":{
        "author": {"$arrayElemAt":["$author",0]}
    }}])