skip to Main Content

There is a document

{i:[1,2,3,4,5,6]}

and need to find by array element value with specified index:

find({ $and: [ {"i.0": 1}, {"i.1": 2} ] })

However, this can not take vantadge of index of createIndex({i:1})
This kind index seems only work for elemMatch like:

find({ i: { $elemMatch: { $gte: 80, $lt: 85 } } })

Does there have anyways to create index which useful in finding specified index of array like "i.n"?

2

Answers


  1. What about this:

    db.collection.aggregate([
       {
          $match: {
             $expr: {
                $and: [
                   { $eq: [{ $arrayElemAt: ["$i", 0] }, 1] },
                   { $eq: [{ $arrayElemAt: ["$i", 1] }, 2] }
                ]
             }
          }
       }
    ])
    

    Mongo Playground

    Login or Signup to reply.
  2. You can create an index on the fields like you query them.

    For example, the index

    createIndex({"i.0":1, "i.1":1})
    

    would do a good job of servicing the query

    find({ $and: [ {"i.0": 1}, {"i.1": 2} ] })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search