Let’s say I have some documents that have an array like this:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"letters": ["a","b","c","d"]
},
{
"_id": ObjectId("5a934e000102030405000001"),
"letters": ["a","b"]
},
{
"_id": ObjectId("5a934e000102030405000002"),
"letters": ["a"]
},
{
"_id": ObjectId("5a934e000102030405000003"),
"letters": ["x","a","b"]
}
]
I want to retrieve all the documents whose letters
array start with an n length array. For example: ["a","b"]
So the result would be like this:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"letters": ["a","b","c","d"]
},
{
"_id": ObjectId("5a934e000102030405000001"),
"letters": ["a","b"]
}
]
I have searched on mongo docs and stack overflow, and the only thing that’s close is using $all
operator but that’s not exactly what I want.
I think it could be done by first slicing the array and then matching it with the query array, but I couldn’t find anything.
2
Answers
Query
$letters
*this is like general solution for any array, to make it work you can replace the 2 with the array size, and the
["a" "b"]
with your arrayPlaymongo
You can simply use array index in match query,
0
index fora
value1
index forb
valuePlayground