The query you provided,
db.config.find({name: "sample_config"}, {"data": { $elemMatch: { "last_name": "Bluth" } } })
Breaks down to this
- Find all documents where the name is sample_config
- Project only fields where
data.last_name
is equal to Bluth
.
The key here is that the find
method takes multiple parameters.
function (query, fields, limit, skip, batchSize, options)
These can be found by executing a find
command on the shell without parentheses. This works for all shell commands, and can be quite useful if you forget how to use a command.
db.config.find
To get the result you want, you need to change the query to this:
{name: "sample_config", "data": { $elemMatch: { "last_name": "Bluth" } } }
Note that I removed the }
after "sample_config"
and removed the {
before "data"
, making it a single query document for the find
command instead of a query
and project
document.
UPDATE:
I realize you also want to project the resulting documents do the array field only contains the matching elements. Now we just need to combine your original projection with the new query
db.col.find({name: "sample_config", "data": { $elemMatch: { "last_name": "Bluth" } } }, {"data": { $elemMatch: { "last_name": "Bluth" } } })
This will return documents of the form
{
_id: xxx,
data: [
{ id: xxx, first_name: xxx, last_name: "Bluth" }
]
}
However, according to the docs, this will only return the first matching array element, not all matching elements.
If you need to further project down the data, I would suggest using the aggregation framework, as those operators are more robust.
That could look something like
db.col2.aggregate({$match: {name: "sample_config", "data": { $elemMatch: { "last_name": "Bluth" } } }},{$unwind:"$data"},{$match:{"data.last_name": "Bluth"}},{$replaceRoot:{newRoot:"$data"}})
Which results in the following output
{ "id" : 1, "first_name" : "George", "last_name" : "Bluth" }
{ "id" : 2, "first_name" : "Janet", "last_name" : "Bluth" }
{ "id" : 2, "first_name" : "Janet", "last_name" : "Bluth" }
From these original documents
{ "_id" : ObjectId("5c5b025fea781cb935c975ae"), "name" : "sample_config", "data" : [ { "id" : 1, "first_name" : "George", "last_name" : "Bluth" }, { "id" : 2, "first_name" : "Janet", "last_name" : "Bluth" } ] }
{ "_id" : ObjectId("5c5b0283ea781cb935c975af"), "name" : "sample_config", "data" : [ { "id" : 1, "first_name" : "George", "last_name" : "Dole" }, { "id" : 2, "first_name" : "Janet", "last_name" : "Bluth" } ] }
{ "_id" : ObjectId("5c5b028bea781cb935c975b0"), "name" : "sample_config", "data" : [ { "id" : 1, "first_name" : "George", "last_name" : "Dole" }, { "id" : 2, "first_name" : "Janet", "last_name" : "Johnson" } ] }
You can find the docs on these operators here: