How can I get an array of all the doc ids in MongoDB? I only need a set of ids but not the doc contents.
Using Java programCreate a MongoDB client by instantiating the MongoClient class. Connect to a database using the getDatabase() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method.
MongoDB provides a function with the name findById() which is used to retrieve the document matching the 'id' as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified 'id', it returns null.
To find a specific amount of records, use LIMIT() in MongoDB. The method accepts one number type argument, which is the number of documents that you want to be displayed.
Architecturally, by default the _id field is an ObjectID, one of MongoDB's BSON types. The ObjectID is the primary key for the stored document and is automatically generated when creating a new document in a collection.
You can do this in the Mongo shell by calling map
on the cursor like this:
var a = db.c.find({}, {_id:1}).map(function(item){ return item._id; })
The result is that a
is an array of just the _id
values.
The way it works in Node is similar.
(This is MongoDB Node driver v2.2
, and Node v6.7.0
)
db.collection('...') .find(...) .project( {_id: 1} ) .map(x => x._id) .toArray();
Remember to put map
before toArray
as this map
is NOT the JavaScript map
function, but it is the one provided by MongoDB and it runs within the database before the cursor is returned.
One way is to simply use the runCommand API.
db.runCommand ( { distinct: "distinct", key: "_id" } )
which gives you something like this:
{ "values" : [ ObjectId("54cfcf93e2b8994c25077924"), ObjectId("54d672d819f899c704b21ef4"), ObjectId("54d6732319f899c704b21ef5"), ObjectId("54d6732319f899c704b21ef6"), ObjectId("54d6732319f899c704b21ef7"), ObjectId("54d6732319f899c704b21ef8"), ObjectId("54d6732319f899c704b21ef9") ], "stats" : { "n" : 7, "nscanned" : 7, "nscannedObjects" : 0, "timems" : 2, "cursor" : "DistinctCursor" }, "ok" : 1 }
However, there's an even nicer way using the actual distinct
API:
var ids = db.distinct.distinct('_id', {}, {});
which just gives you an array of ids:
[ ObjectId("54cfcf93e2b8994c25077924"), ObjectId("54d672d819f899c704b21ef4"), ObjectId("54d6732319f899c704b21ef5"), ObjectId("54d6732319f899c704b21ef6"), ObjectId("54d6732319f899c704b21ef7"), ObjectId("54d6732319f899c704b21ef8"), ObjectId("54d6732319f899c704b21ef9") ]
Not sure about the first version, but the latter is definitely supported in the Node.js driver (which I saw you mention you wanted to use). That would look something like this:
db.collection('c').distinct('_id', {}, {}, function (err, result) { // result is your array of ids })
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