Is there any way to pass array of indexes to mongodb and get elements from array at that indexes

Viewed 108

I have an mongodb doc with an array of 100 elements and I want to get multiple elements from this array at given indexes given in query array. example : let query = [2,3,5,6,7,4,44,32,71]; So, I want to get elements in array in mongodb doc at indexes given in query array.

2 Answers

If you want filter data on mongo side, you can do like this.

db.getCollection('feed').find({
  "_id" : {
    "$in" : [
      ObjectId("55880c251df42d0466919268"), 
      ObjectId("55bf528e69b70ae79be35006")
    ]
  }
});

If not,

const filteredResult = items.filter(item => query.includes(item._id));
console.log(filteredResult);

there's no built-in mongodb operator that can support your requirement out of the box but... you can achieve it with a very difficult to read aggregation pipeline like this:

var query = [1, 3, 5]

db.Collection.aggregate(
[
    {
        $match: { "_id": ObjectId("5fd33ddd23505e1538b96116") }
    },
    {
        $set: {
            Array: {
                $map: {
                    input: {
                        $filter: {
                            input: {
                                $map: {
                                    input: "$Array",
                                    as: "x",
                                    in: {
                                        Position: { $add: [{ $indexOfArray: ["$Array", "$$x"] }, 1] },
                                        Value: "$$x"
                                    }
                                }
                            },
                            as: "xx",
                            cond: { $in: ["$$xx.Position", query] }
                        }
                    },
                    as: "xxx",
                    in: "$$xxx.Value"
                }
            }
        }
    }
])

https://mongoplayground.net/p/_b1hzeUPlmu

Related