Reputation: 889
Is there a way to push all the documents of a given collection in a array? I did this but is there any quicker way?
var ops = [];
db.getCollection('stock').find({}).forEach(function (stock) {
ops.push(stock);
})
PS: I use Mongo 3.4
Upvotes: 0
Views: 57
Reputation: 10918
You could as well use $facet which will allow you to create the array on the server side - provided the resulting document array is no bigger than 16MB in which case you'll get an exception:
db.stock.aggregate({
$facet: {
ops: [ { $match: {} } ]
}
})
In order to reduce the amount of data returned you could limit the number of returned fields in the above pipeline (instead of an empty $match stage - which is a hack anyway - you would then use $project).
Upvotes: 0
Reputation: 93073
You can just use the toArray
function on the cursor that's returned from find, like this:
var ops = db.getCollection('stock').find({}).toArray();
Note: As with your original solution, this might suffer with performance if the stock
collection contains millions of documents.
As an aside, you can use db.stock
directly to shorten the query a little bit:
var ops = db.stock.find({}).toArray();
Upvotes: 1