Home > Back-end >  Match beginning of array with another array in mongodb
Match beginning of array with another array in mongodb

Time:06-03

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 ["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.

CodePudding user response:

You can simply use array index in match query,

  • check 0 index for a value
  • check 1 index for b value
db.collection.find({
  "letters.0": "a",
  "letters.1": "b"
})

Playground

CodePudding user response:

Query

  • slice and take the first 2 of $letters
  • check if equal with ["a" "b"]

*if you want to do this for any array, replace the 2 with the size of that array

Playmongo

aggregate(
[{"$match": {"$expr": {"$eq": [{"$slice": ["$letters", 2]}, ["a", "b"]]}}}])
  • Related