1

I am struggling with a MongoDB request. I have a Play schema that holds an array of Move objects. Each Move object holds a reference to a Player in the form of an ObjectID. Following this question I tried to do

{ 'moves.player': { $elemMatch : { $ne : playerId } } }

where playerId holds an ObjectID. However I get the error

Error: Can't use $elemMatch with ObjectId

I have also tried the following

{ 'moves.player.str': { $elemMatch : { $ne : playerId.toString() } } }

but it doesn't find the proper documents... Any ideas?

Example

Some Play records:

A = {
    "moves": [
        { player: { $oid: "56f32fe2f41638de3b3e4773" } },
        { player: { $oid: "56f32fe2f41638de3b3e4774" } }
    ]
}
B = {
    "moves": [
        { player: { $oid: "56f32fe2f41638de3b3e4773" } }
    ]
}

Query for playerId = "56f32fe2f41638de3b3e4773" should only return object A, since it is the only one that has an array of moves where at least one of the players is different from 56f32fe2f41638de3b3e4773.

2
  • 1
    Unfortunately. Even though you found your own solution ( or at least you think you did ) this question does not show the document structure that you are in fact querying. Therefore it is of little use to anyone as an example, and is a very unclear question. Showing a sample document you expect to match would make it better. Commented Mar 24, 2016 at 6:48
  • Good suggestion, added an example, this might help understanding the problem. Was stuck on this one for a long time, so I suspect it could be useful to someone else. Commented Mar 24, 2016 at 7:10

1 Answer 1

3

OK, found out where the problem was... Just do

{ "moves": { $elemMatch: { "player": { $ne : playerId } } } }

and it works out fine!

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

3 Comments

Pretty sure that if your data looks like I "think" it does ( already told you it's not good to ask questions without a sample for others to solve the problem ) then simply { "moves.player": { "$ne": playerId } } is enough. You only need $elemMatch when "two or more" conditions for properties need to be met. Single property inspection can be done with plain "dot notation".
$ne would not return the Play records where one of the moves was assigned to the player with playerId, so in my example wouldn't return neither A nor B...
Ah. Now I get it. Your answer is the right approach.

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.