Search code examples
node.jsarraysmongodbperformancesub-array

Get Index of Sub Array in MongoDB


I have the following array:

const universitiesSchema = new Schema({
  name: {
    type: String,
    required: [true, 'Required']
  }, 
  users: {
    type:[Schema.Types.ObjectId], 
  }
});

I would like to get the index based on particular value in the array.

const unis = await Universities.findOne({ _id: university_id });  
const userIndex = unis.users.indexOf(new mongoose.Types.ObjectId(user_id));

It works, but I am expecting the users Array to get quite large, and I don't want this to be done on the web server. I prefer if MongoDB handles it


Solution

  • run aggregation function like this

    db.Universities.aggregate( [ 
    { $match : { _id : new mongoose.Types.ObjectId(university_id) } },
    {
       $project: {
          index: { $indexOfArray: [ "$users", new mongoose.Types.ObjectId(user_id) ] }
       }
    } ] )
    

    this should work. for more clarification please check MongoDB documentation..