Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

The following is my data that is stored as a document database:

> db.parameters.find({})

{ "_id" : ObjectId("56cac0cd0b5a1ffab1bd6c12"), "name" : "Speed", "groups" : [ "

123", "234" ] }

> db.groups.find({})

{ "_id" : "123", "name" : "Group01" }

{ "_id" : "234", "name" : "Group02" }

{ "_id" : "567", "name" : "Group03" }

I want to add a parameter _id to make a query return all groups that are within the group's array of the given document in the parameters table.

Please assist me to find a solution that would work from PyMongo DB interface

1 Answer

0 votes
by (107k points)
edited by

You can simply perform this in a single query by applying the aggregation framework. You just have to run an aggregation pipeline that utilizes the $lookup operator to do a left join from the argument collection to the group's collection.

Consider running the following pipeline:

db.parameters.aggregate([

    { "$unwind": "$groups" },

    {

        "$lookup": {

            "from": "groups",

            "localField": "groups",

            "foreignField": "_id",

            "as": "grp"

        }

    },

    { "$unwind": "$grp" }

])

Sample Output

/* 1 */

{

    "_id" : ObjectId("56cac0cd0b5a1ffab1bd6c12"),

    "name" : "Speed",

    "groups" : "123",

    "grp" : {

        "_id" : "123",

        "name" : "Group01"

    }

}

/* 2 */

{

    "_id" : ObjectId("56cac0cd0b5a1ffab1bd6c12"),

    "name" : "Speed",

    "groups" : "234",

    "grp" : {

        "_id" : "234",

        "name" : "Group02"

    }

}

If you want more information regarding the MongoDB then do refer to the following blog. 

Also, have a look at this professional Full Stack Developer Training, designed to enhance your skills in the field.

Related questions

0 votes
1 answer
asked Mar 15, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Mar 14, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Feb 2, 2020 in Web Technology by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...