Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

finding object from array of objects in Mongodb

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

mongoplayground


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

mongoplayground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading