query in mongoDB with json nested

0

good morning.

I have the following collection in mongoDb:

{
"signupDate": "2018-11-22T19:14:02.047Z",
"_id": "5bf700269e5b59276885eda5",
"userName": "pruebas",
"email": "[email protected]",
"password": "abc1234",
"interests": "{\"followEmails\": false, \"dogs\": [{\"raza\": \"poodle\", 
\"age\": 2},{\"raza\": \"poodle\", \"age\": 7}]}",
"phone": "00000",
"imgProfile": "img/profile/user.png",
"Emailverify": false,
"passwordHas": 
"$2a$10$y1Wty9OUQUmOB5B90kEDY.DWR6umNgGURznJxkhdpI.pbNGelS/Qe",
"__v": 0
},

I need to create a query that returns to me the users who have in their field interest- > dogs = a certain breed of dog. I have already tried several queries since robomongo but I still do not give.

This query returns all the users that contain in the object interests the key dogs.

db.getCollection('users').find({},{interests: [ "dogs"]})
    
asked by user7649760 23.11.2018 в 16:50
source

1 answer

0

I have my doubt if what you keep in the 'interests' field is a JSON object (document in MongoDB) or is a String, in the case that it was String you would have to change to the JSON format.

In the case of a JSON, what you need to do is a subdocument search:

db.getCollection('users').find({userName: /*user*/ , 'interests.dogs.raza': /*raza*/}, {})

This query will look for all users that you indicate in ' user ' that you have in the 'interests' field, in the 'dogs' field and will search the entire document array, document by document, the field 'race' that is equal to the value ' race '. From there you would have to project / filter the document you want to return.

I hope I have helped you.

Greetings

    
answered by 24.11.2018 / 12:55
source