Andrei Gavrila
Andrei Gavrila

Reputation: 863

Mongodb Array ElemMatch

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.

Upvotes: 4

Views: 8476

Answers (2)

Robert Stam
Robert Stam

Reputation: 12187

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.

Upvotes: 8

Carlo Micieli
Carlo Micieli

Reputation: 167

Have you tried quering keywords like the other keys in your document? The driver will returns the documents that contain the provided keyword

Bye

Upvotes: 1

Related Questions