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']
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
Unlike relational database models, MongoDB documents can have fields which have values as arrays. The prototypical example in almost all MongoDB documentation is a document having a tags field, whose value is an array of strings, such as ["NoSQL", "Ruby", "MongoDB"] .
Specify a Query Condition on a Field Embedded in an Array of Documents. If you do not know the index position of the document nested in the array, concatenate the name of the array field, with a dot ( . ) and the name of the field in the nested document.
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"
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With