Home > Blockchain >  finding object from array of objects in Mongodb
finding object from array of objects in Mongodb

Time:03-03

const Schema = new Schema({
    queueId: {
        type: String,
        required: true,
        index: {
            unique: true
        }
    },
    players: {
        type: [
            {
                ID: {
                    type: String,
                    required: true,
                    index: {
                        unique: true
                    },
                    default: 'null'
                },
                name: {
                    type: String,
                    required: true,
                    default: 'null',
                },
                queueId: {
                    type: String,
                    required: true,
                    default: 'null'
                }
            }
        ],
        required: true,
        default: []
    },
    isAvailable: {
        type: Boolean,
        required: true,
        default: true
    },
    isFull: {
        type: Boolean,
        required: true,
        default: false
    }
});

How do I use findOne() to get the object from players which is an array

Im currently trying this code but it returns null

const doc = await List.findOne({ players: { ID: 'id' } });

basically players is an array and I want to find ID from the players array of objects and get the document.

CodePudding user response:

db.collection.find({
  "players.ID": "1"
},
{
  "players.$": 1
})

mongoplayground


db.collection.find({
  "players.ID": "1"
})

mongoplayground

  • Related