Search code examples
mongodb

How to query an array of _id in MongoDB?


I have collection Collection1 and I need to fetch an array like: [id1, id2, id3, ...] (array which consist of _id`s for every element in this collection). Is there any way to do this query with MongoDB tools ? Thank you!


Solution

  • You will have to use cursor.toArray() function on result of find having a projection document projecting only _id i.e ObjectId() value

    MongoDB Enterprise > db.users.find().pretty()
    {
            "_id" : ObjectId("570e1d465a44f125ef156791"),
            "name" : "Name1",
            "age" : 22,
            "gender" : "M"
    }
    {
            "_id" : ObjectId("570e1e1d5a44f125ef156792"),
            "name" : "Name2",
            "age" : 21,
            "gender" : "F"
    }
    {
            "_id" : ObjectId("570e1e485a44f125ef156793"),
            "name" : "Name3",
            "age" : 22,
            "gender" : "M"
    }
    {
            "_id" : ObjectId("570e28d45a44f125ef156794"),
            "name" : "Name4",
            "age" : 21,
            "gender" : "F"
    }
    { "_id" : 123 }
    MongoDB Enterprise > db.users.find({}, {_id:1}).toArray()
    [
            {
                    "_id" : ObjectId("570e1d465a44f125ef156791")
            },
            {
                    "_id" : ObjectId("570e1e1d5a44f125ef156792")
            },
            {
                    "_id" : ObjectId("570e1e485a44f125ef156793")
            },
            {
                    "_id" : ObjectId("570e28d45a44f125ef156794")
            },
            {
                    "_id" : 123
            }
    ]
    MongoDB Enterprise >
    

    As an addition you can also use:

    MongoDB Enterprise > db.users.distinct("_id")
    [
            123,
            ObjectId("570e1d465a44f125ef156791"),
            ObjectId("570e1e1d5a44f125ef156792"),
            ObjectId("570e1e485a44f125ef156793"),
            ObjectId("570e28d45a44f125ef156794")
    ]
    MongoDB Enterprise >