Toby Chambers
Toby Chambers

Reputation: 41

Mongoose, more efficient way of searching through array?

I'm working with Mongoose and MongoDB - and am searching through a nested array in my document for an object with a specified ID.

Currently, I am doing the following:

    const dbGuild = guildModel.findById(guildId);
    for (member of dbGuild.guildData.members) {
      if (member._id === mentionedUserId) {
        console.log(member.economy.hand);
        console.log(member.economy.bank);

        member.economy.bank = 5000;
        const updated = await dbGuild.save();
      }
    }

Where I am looping through every single value in that array - however this seems very inefficient as it would mean that if there was a large amount of data in the array I would be querying a huge amount of data.

Is it possible to do this on the database? And only return the single object with that id.

Upvotes: 3

Views: 154

Answers (1)

Syed Ali Shahzil
Syed Ali Shahzil

Reputation: 1224

For example if you have data like that

enter image description here

if you know the position of element in the array

db.roundTest.findAndModify({
       query: { _id : ObjectId('60c916684bd16901f36efb3a') },
       update: { $set: { "holes.$[elem].holeGross" : 8 } },
       arrayFilters: [ { "elem.no": 1 } ]
    })

other method to update a single object in the array

db.document.update({
       "_id":"idofobject"
    },
   {
     "$set":{
      "holes.$.name" : "Augmon" //you should use name of yourfiled 
   }})

for more detail read that article Update single (same) field in every object of an array

watch this video to see how to use these queries update monogoDB Array Elements

Upvotes: 1

Related Questions