1

I've this query:

string jsonquery = "{
$and : [{
        WordsData : {
            $elemMatch : {
                UserId : ObjectId('57a87f5cc48933119cb96f93'),
                UserId : ObjectId('57a87f5cc48933119cb96f94')
            }
        }
    }, {
        WordsData : {
            $not : {
                $elemMatch : {
                    MatchType : 2
                }
            }
        }
    }
]
}"

if i execute it in a mongo console works correctly!
I'm trying to run this query in a c# program. Running the same json query i got the following error:

BsonDocument doc = BsonSerializer.Deserialize<BsonDocument>(jsonquery);
[Error] --> {"Duplicate element name 'UserId'."}

Why doesn't works in c# ?

profesor79
  • 9,213
  • 3
  • 31
  • 52
Marco
  • 656
  • 9
  • 28
  • 1
    You can't have two `UserId` fields in your `$elemMatch` object. The shell is just ignoring one of them. – JohnnyHK Aug 10 '16 at 13:28
  • Why this problem only in .NET ? Because the same query works correctly for example in RoboMongo client console! How can i obtain the same result without passing "UserId" multiple times for the same $elemMatch? What i'm trying to do, is a query which return all documents that have in WordsData array one element with UserId = {57a87f5cc48933119cb96f93} and one other element with UserId = {57a87f5cc48933119cb96f94} – Marco Aug 10 '16 at 13:36
  • could you post example document? – profesor79 Aug 10 '16 at 13:49
  • @profesor79: see my previous post [Possible query with MongoDB](http://stackoverflow.com/questions/38854787/possible-query-with-mongodb/38854921#38854921) – Marco Aug 10 '16 at 13:55

1 Answers1

1

You need to nest multiple $elemMatch inside of a $and expression. See this this thread for an example.

Think of JSON as a map -- if you have duplicate keys they are going to override each other and cause errors and/or unexpected results.

Community
  • 1
  • 1
helmy
  • 9,068
  • 3
  • 32
  • 31
  • You are suggesting something like this: `{ $and: [{ WordsData: { $elemMatch: { UserId: ObjectId(\"{0}\") } } },{ WordsData: { $elemMatch: { UserId: ObjectId(\"{1}\") } } }` – Marco Aug 10 '16 at 14:53