2

Below is code to retrieve all documents in collection.

db.collection('movies', function(err, collectionref) {          
    // find all documents in a collection that have foo: "bar"
    var cursor = collectionref.find({});
    cursor.toArray(function(err, docs) {
        // gets executed once all items are retrieved
        res.render('movie', {'movies': docs});
    });
});

I want the id of all documents in collection using node js.

2
  • 1
    Are you talking about _id?? If yes , then its there in your docs Commented Jan 11, 2016 at 7:22
  • Yes i want _id..how to iterate on docs to get all ids. Commented Jan 11, 2016 at 7:29

2 Answers 2

1

You can iterate on cursor object to get _id like this:

var cursor = db.inventory.find( {} );
while (cursor.hasNext()) {
  console.log(tojson(cursor.next())._id);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Fortunately, since it's just JavaScript, you're provided with normal collection iterators:

// find all documents that are "movies"
db.movies.find({})
.map(function(doc) {
  // iterate and return only the _id field for each document
  return doc._id;
});

The more formal MongoDB-ish name for this is cursor.map, which:

Applies function to each document visited by the cursor and collects the return values from successive application into an array.

The example in the docs in the link I provided is also pretty clear:

db.users.find().map( function(u) { return u.name; } );

This functionality mimics the native Array.prototype.map in many ways (I would suggest reading those docs as well if you are not familiar with that method).

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.