Rabin Limbu
Rabin Limbu

Reputation: 55

Query Document With Array In MongoDB C#

I am using MongoDB C# API.

Below is MongoDB document structure:

{
  "_id" : ObjectId("4fc6aaaef8594f055c4169f2"),
  "Status" : "A",
  "productTagContainerId" : "ptag_item_45688ab87bf796",
  "productTag" : [{
    "id" : "root",
    "idText" : "",
    "tagSource" : "Category",
    "value" : "rootValue"
  },
  "id" : "test1",
  "idText" : "",
  "tagSource" : "Category",
  "value" : "test1Value"
},

"id" : "test2",
"idText" : "",
  "tagSource" : "Category",
  "value" : "test2Value"
}]
}

I am trying to get this document only when "value" in "productTag" matches test1Value and test2Value respectively. I tried query like below but returning null:

finalQuery = Query.ElemMatch("productTag",
   Query.And(
       Query.EQ("value", "test1Value"),
       Query.EQ("value", "test2Value")
   )
);

Please advise!!!

Upvotes: 0

Views: 1337

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

By using ElemMatch, your query will only match a document where both of your query terms are satisfied in the same productTag array element (which is impossible in this case).

Instead, use a query that uses dot notation like this:

var finalQuery = Query.And(
    Query.EQ("productTag.value", "test1Value"),
    Query.EQ("productTag.value", "test2Value")
);

Upvotes: 2

Related Questions