Querying MongoDB to match in the first item in an array

后端 未结 2 1651
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 06:26

I\'m aware of the $in operator, which appears to search for an item\'s presence in array, but I only want to find a match if the item is in the first position i

相关标签:
2条回答
  • 2020-12-03 07:02

    You can use dot notation for array indexes:

    db.products.find({"imgs.0": "http://foo.jpg"})
    

    Here is an excerpt from the relevant documentation for dot notation.

    MongoDB uses the dot notation to access the elements of an array and to access the fields of a subdocument.

    To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

    '<array>.<index>'

    Additionally, here is a link to the relevant array documentation.

    0 讨论(0)
  • 2020-12-03 07:03

    I believe you want imgs.0. eg, given your example document, you want to say: db.products.find({"imgs.0": "http://foo.jpg"})

    Be aware that referencing array indexes only works for the first-level array. Mongo doesn't support searching array indexes any deeper.

    0 讨论(0)
提交回复
热议问题