0

I have a json document which has a structure as is displayed below:

{
    "125": {
        "name": "sample name one",
        "age" : 22,
    },
    "126": {
        "name": "sample name two",
        "age" : 27,
    },
    "127": {
        "name": "sample name three",
        "age" : 21,
    }
}

I want to return the object represented by 125, i.e. the following object :

{
    "name": "sample name one",
    "age" : 22,
}

I have tried the following query from the console, but I cannot get the result I need: db.persons.find({"125": {$exists: true}}).

I would like to know how to query the database to return the data that I need. Thank you for any help.

Community
  • 1
  • 1
kushaldsouza
  • 710
  • 5
  • 12
  • 36

2 Answers2

1
db.persons.find({"125": {$exists: true}})

would return whole document, that has "125" key, not only the "125" key.

If You need to return only the "125", You should use projection, passing it as second argument to find:

db.persons.find({"125": {$exists: true}}, {"125": 1})

then You will get documents containing "125" key, without any other keys (except _id of that document)

To omit _id of document, You need to use:

db.persons.find({"125": {$exists: true}}, {"125": 1, _id: 0})

EDIT:

Did You consider using array for those subdocuments with repeating schema? It would be more natural, idiomatic, and also give You some additional possibilities.

Jarema
  • 3,291
  • 2
  • 17
  • 30
0

In mongo search by JSON key / field / name, use $exists operator

db.things.find( { '125' : { $exists : true } } );
Hiren Makwana
  • 1,976
  • 2
  • 13
  • 28