You can do this in MongoDb version 3.2+ with aggregation.
Query:
db.Notebook.aggregate(
{
$project: {
"notes": {
$filter: {
input: "$notes",
as: "note",
cond: {
$eq: [ "$$note.title", "Hello MongoDB" ]
}
}
}
}
}
)
Result:
{
"_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
"notes" : [
{
"title" : "Hello MongoDB",
"content" : "Hello MongoDB"
}
]
}
$$ used here to access the variable. I used here to access the newly created note
variable inside the $filter
.
You can find additional details in the official documentation about $filter, $eq and $$.
$filter: Selects a subset of an array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.
$eq: Compares two values and returns true/false when the values are equivalent or not (...).
$$: Variables can hold any BSON type data. To access the value of the variable, use a string with the variable name prefixed with double dollar signs ($$).
Note:
Justin Jenkin's answer is outdated and kop's answer here doesn't return multiple documents from the collection. With this aggregation query, you can return multiple documents if needed.
I needed this and wanted to post to help someone.