Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb Array ElemMatch

Tags:

c#

mongodb

I have a collection of documents:

  "_id" : ObjectId("500d1aa9cf6640c15214fc30"),
  "Title" : "Title0",
  "Description" : "Description0",
  "Keywords" : ["Keyword000", "Keyword001", "Keyword002", "Keyword003", "Keyword004", "Keyword005", "Keyword006", "Keyword007", "Keyword008", "Keyword009"],
  "Category" : 0

I would like to query for items that have one keyword:

var query = Query.ElemMatch("Keywords", Query.EQ(XXX, "Keyword003"));

I have no idea on what to query on Query.EQ.


By turning the example into:

"_id" : ObjectId("500d4393cf6640c152152354"),
"Title" : "Title0",
"Description" : "Description0",
"Keywords" : [{
  "Value" : "Keyword000"
}, {
  "Value" : "Keyword001"
}],
"Category" : 0

And querying by

var query = Query.ElemMatch("Keywords", Query.EQ("Value", "Keyword001"));

I have no problem on getting the results.

Thank you.

like image 748
Andrei Gavrila Avatar asked Jan 17 '23 00:01

Andrei Gavrila


1 Answers

The MongoDB query engine treats queries of the form { x : 123 } differently when x is an array. It matches any document where the x array contains 123. See:

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray

In your case, the query:

Query.EQ("Keywords", "Keyword003")

will match any document where the Keywords array contains "Keyword003". It might also contain other values, but that doesn't matter.

ElemMatch is only needed when the array is an array of embedded documents and you want to write a complex test against each of the embedded documents.

like image 147
Robert Stam Avatar answered Jan 25 '23 22:01

Robert Stam