0
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.

1 Answer 1

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

mongoplayground


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

mongoplayground


db.collection.aggregate([
  {
    $match: {
      "players.ID": "1"
    }
  },
  {
    $unwind: "$players"
  },
  {
    $match: {
      "players.ID": "1"
    }
  }
])

mongoplayground

Sign up to request clarification or add additional context in comments.

4 Comments

Any way to get this using findOne()?
@Firez should work just like the second part of answer
@cmgchess second part gives an array, I am trying to get an object. I know using [0] (limit will be 1) will give me an object but I would still like to know if I could this in object form.
@Firez My third answer use aggregate $unwind

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.