Home > Net >  how to find both string and string array in mongodb
how to find both string and string array in mongodb

Time:11-10

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.

CodePudding user response:

With dot notation.

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

Sample Mongo Playground

  • Related