9

I have this Collection

{
    "_id" : ObjectId("55555555ffffff000010200a"),  
    "name" : "foo"
}

{
    "_id" : ObjectId("55555555ffffff000010200e"),
    "name" : "bar"
}

{
    "_id" : ObjectId("55555555ffffff000010200f"),    
    "name" : "baz"
}


{
    "_id" : ObjectId("55555555ffffff000010200b"),
    "name" : "biz"
}

and I want an array ids

I did this

db.mycollection.find({}, {_id: 1})

and return

{
    "_id" : ObjectId("55555555ffffff000010200a")
}

{
    "_id" : ObjectId("55555555ffffff000010200e")
}

{
    "_id" : ObjectId("55555555ffffff000010200f")
}

{
    "_id" : ObjectId("55555555ffffff000010200b")
}

{
    "_id" : ObjectId("55555555ffffff000010200c")
}

{
    "_id" : ObjectId("55555555ffffff0000103111")
}

Can I have an array? id['55555555ffffff0000103111','55555555ffffff0000103111','555555555ffffff0000103111','55555555ffffff0000103111']

1
  • I have edited my answer with another option. Check if that's more suited to what you are looking for. Commented Mar 17, 2014 at 15:08

2 Answers 2

12

Option 1: If an array of subdocuments is acceptable, you can just append .toArray() to the find query.

> db.test.find({}, {_id:1}).toArray()
[
        {
                "_id" : ObjectId("53270b12d111b9bf595f4270")
        },
        {
                "_id" : ObjectId("53270b14d111b9bf595f4271")
        },
        {
                "_id" : ObjectId("53270b16d111b9bf595f4272")
        }
]

Option 2: Another option is to use the aggregation framework.

> db.test.aggregate([{$group:{_id:null, ids:{$push:"$_id"}}}, {$project:{_id:0, ids:1}}])
{
        "result" : [
                {
                        "ids" : [
                                ObjectId("53270b12d111b9bf595f4270"),
                                ObjectId("53270b14d111b9bf595f4271"),
                                ObjectId("53270b16d111b9bf595f4272")
                        ]
                }
        ],
        "ok" : 1
}

Option 3: Or you can use forEach in the shell like this:

> var myIds = new Array()
> db.test.find({},{_id:1}).forEach(function(myDoc){myIds.push(myDoc._id.str)})
> myIds
[
        "53270b12d111b9bf595f4270",
        "53270b14d111b9bf595f4271",
        "53270b16d111b9bf595f4272"
]
Sign up to request clarification or add additional context in comments.

Comments

1

Use distinct to turn a single column into an array:

db.mycollection.distinct('_id', function(err, list){
 //list is an array of ObjectId
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.