skip to Main Content

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


  1. Query

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

    *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 array

    Playmongo

    aggregate(
    [{"$match": {"$expr": {"$eq": [{"$slice": ["$letters", 2]}, ["a", "b"]]}}}])
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search