diegoaguilar
diegoaguilar

Reputation: 8376

How to query according to an specific document matching criteria inside an array in a MongoDB doc?

I have a collection lineups which got the players attribute being an array, players looks like this:

{
    players: [{id: "ac52", points: 24, captain: false}, {id: "as4f", points: 15, captain:true}]
}

How can I find those lineups with a document with id: ac52 and points distinct of 24 inside players array attribute?

I know and have used $elemMatch but in this case I don't only need to find those inside array with a document with id something but a set of attribute matching a criteria.

So, for example if I have this set of documents:

{
    players: [{id: "ac52", points: 24, captain: false}, {id: "as4f", points: 15, captain:true}]
}

{
    players: [{id: "ac52", points: 26, captain: false}, {id: "as4f", points: 15, captain:true}]
}

{
    players: [{id: "ac52", points: 11, captain: false}, {id: "as4f", points: 15, captain:true}]
}

I'd need my query to output:

{
    players: [{id: "ac52", points: 26, captain: false}, {id: "as4f", points: 15, captain:true}]
}

{
    players: [{id: "ac52", points: 11, captain: false}, {id: "as4f", points: 15, captain:true}]
}

Edit:

I've tried with:

db.lineup.count({"matchDate.round": 6, $and: [{players: {$elemMatch: {id: "p106212", currentRoundPoints: {$ne: 8}}}}, {players: {$elemMatch: {id: "p106212", currentRoundPoints: {$ne: 16}}}}]})

Getting not expected results

Upvotes: 1

Views: 45

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

To find the lineups docs that contain a players element with an id of 'ac52' and points something besides 24 you can combine both those clauses in a single $elemMatch:

db.lineups.find({
    players: {$elemMatch: {
        id: 'ac52',
        points: {$ne: 24}
    }}
})

Upvotes: 2

Related Questions