Skip to content
Advertisement

Is there a way to search for a value in mongodb in object with arrays, and the value could be present in any object of that array

This is the structure:

{"_id":"_vz1jtdsip",
"participants":{
   "blue":["finettix"]
    "red":["EQm"]
    },
"win":"red","
__v":0}

and i have many documents as this, I want to search in participants blue/red for a specific name and to return that document. For code I`m using javascript, I tried something like this:

await gamesSchema.find().where('participants.red').in(player[0].Nickname);

but this only return participants.red, I could make another call for blue but I would like them in the order as they are in database, so I`m asking if there is a method to search at once.

Advertisement

Answer

Try an $or condition :

await gamesSchema
    .find({
        $or : [{
            "participants.red" : player[0].Nickname
        },{
            "participants.blue" : player[0].Nickname
        }]
    })
    .lean() // Returns simple JSON, not a collection of Mongoose objects
    .exec(); // Returns a true Promise, not a thenable. Good with await
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement