9

If I have a mongodb collection users like this:

{
  "_id": 1,
  "name": {
    "first" : "John",
    "last" :"Backus"
  },
}

How do I retrieve name.first from this without providing _id or any other reference. Also, is it possible that pulling just the `name^ can give me the array of embedded keys (first and last in this case)? How can that be done?

db.users.find({"name.first"}) didn't work for me, I got a:

SyntaxError "missing: after property id (shell):1

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Swapnil
  • 8,201
  • 4
  • 38
  • 57

3 Answers3

31

The first argument to find() is the query criteria whereas the second argument to the find() method is a projection, and it takes the form of a document with a list of fields for inclusion or exclusion from the result set. You can either specify the fields to include (e.g. { field: 1 }) or specify the fields to exclude (e.g. { field: 0 }). The _id field is implicitly included, unless explicitly excluded.

In your case, db.users.find({name.first}) will give an error as it is expected to be a search criteria.

To get the name json : db.users.find({},{name:1})

If you want to fetch only name.first

db.users.find({},{"name.first":1})

Mongodb Documentation link here

Rahul
  • 15,979
  • 4
  • 42
  • 63
  • 3
    While using it in mongo shell at least, I need to put quotes around "name.first" in case I need to fetch only name.first – Swapnil Dec 18 '12 at 06:49
0

To fetch all the record details: db.users.find({"name.first":""}) To fetch just the name or specific field: db.users.find({{},"name.X":""}); where X can be first, last .

dot(.) notation can be used if required to traverse inside the array for key value pair as db.users.find({"name.first._id":"xyz"});

0

In 2022

const cursor = db
  .collection('inventory')
  .find({
    status: 'A'
  })
  .project({ item: 1, status: 1 });

Source: https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/

Yannick Lescure
  • 109
  • 2
  • 3