How could I get one element from array from Mongo document with following structure:
{
array : [
{type: 'cat', name: 'George'}
{type: 'cat', name: 'Mary'}
{type: 'dog', name: 'Steve'}
{type: 'dog', name: 'Anna'}
]
}
For example I need to get Steve, in this case result must looks so:
{
array : [
{type: 'dog', name: 'Steve'}
]
}
or so: {type: 'dog', name: 'Steve'}
I know how make it while publishing but I need to make it on client side where whole array is available, I could return this value from array using forEach, but I'm searching more elegant way (using Mongo query).
Match an Array To specify equality condition on an array, use the query document { <field>: <value> } where <value> is the exact array to match, including the order of the elements.
The $pull operator removes from an existing array all instances of a value or values that match a specified condition. The $pull operator has the form: { $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
Use $match With $eq to Find Matching Documents in an Array in MongoDB. Use $match With $all to Find Matching Documents in an Array in MongoDB.
Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.
Use the positional operator($
) to project only the first matching sub document.
db.t.find({"array":{"type":"dog", "name":"Steve"}},{"array.$":1})
Using meteor
, you would have to stick to aggregation, since the positional
operator does not work:
db.t.aggregate([
{$match:{"array.type":"dog","array.name":"Steve"}},
{$unwind:"$array"},
{$match:{"array.type":"dog","array.name":"Steve"}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With