0

I'm a beginner at MongoDB.

I want to find documents in MongoDB by favorite.foods.

Here are documents

{
  "_id":1,
  "favorite": {
    "color":"red",
    "foods":{
      "fruits":"banana",
      "fastfood":["burger", "sandwich"]
    }
  }
},
{
  "_id":2,
  "favorite": {
    "color":"green",
    "foods":{
      "noodles":"ramen",
      "fastfood":["fries", "burger", "corn dog"]
    }
  }
},
{
  "_id":3,
  "favorite": {
    "color":"red",
    "foods":{
      "soup":"cream soup"
    }
  }
}

I tried to

db.collectionName.find({"favorite.foods":{"fruits":"banana","fastfood":{"$all":["burger", "sandwich"]}}})

but couldn't find id 1...

Please help me.

1 Answer 1

1

With dot notation.

db.collection.find({
  "favorite.foods.fruits": "banana",
  "favorite.foods.fastfood": {
    "$all": [
      "burger",
      "sandwich"
    ]
  }
})

Sample Mongo Playground

Sign up to request clarification or add additional context in comments.

11 Comments

do I have to use dot?
@bob This answer works because it tries to match on 2 different fields inside the favorite.foods object. Your initial attempt is close, but you are trying to match the whole favorite.food object so you cannot fetch the expected document. Thanks YongShun for this clean and concise answer.
And thanks to @ray for the explanation in detail. =)
Hi @bob, you may have a look at the link I shared for the sample query for the embedded documents.
oh, sorry! I was wrong spell. thank :)
|

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.