0

I am fairly new to MongoDB and I am trying to figure out how I can query a collection for a document that contains a specific value in a specific array position. I have a general idea but I am getting syntax errors when I try to use $position so I know I'm off track here despite my best effort with the mongo docs.

As an example document for what I am trying to do, I'll use a recipes database collection:

{
  "_id": ObjectId("1234"),
  "recipeName": "Super tasty cilantro lime chicken",
  "ingredients": ["chicken breast", "cilantro", "lime"]
},
{
  "_id": ObjectId("4321"),
  "recipeName": "Radical Cilantro Dip",
  "ingredients": ["cilantro", "lime", "sour cream"]
}

What is the best method for finding only the document(s) that contains cilantro in the 2nd position of the ingredients array instead of all documents containing cilantro in any position?

styvane
  • 59,869
  • 19
  • 150
  • 156
HellaDev
  • 408
  • 2
  • 8
  • 24

1 Answers1

0

Credit to @Ali Dehghani for the answer!

Try this db.collectionName.find({"ingredients.1": "cilantro"}) – Ali Dehghani

HellaDev
  • 408
  • 2
  • 8
  • 24