Reputation: 55
I have a user.expenses
collection like this
{
userId: ObjectId("62f332b93753ac926ff6ac62"),
expenses: [
{
name: 'electricity',
assigned: 400,
given: 400,
},
{
name: 'restaurant',
assigned: 2100,
given: 0,
}
]
}
I will get userId
and expenses.name
(electricity) from the request. I need to check if the user.expenses
collection has any expenses
document whose name is electricity
and assigned
is not equal to given
.
I used $elemMatch
and could check if there are any embedded documents whose name
is electricity
.
db.user.expenses.find({
userId: ObjectId('62f332b93753ac926ff6ac62'),
expenses: {
$elemMatch: {
name: 'electricity',
},
},
});
I also tried to use $where
. But it only can be applied to the top-level document.
Upvotes: 1
Views: 53
Reputation: 8705
Query
$filter
electricity
and assigned!=given
electricity
with assigned!=given
aggregate(
[{"$match":
{"$expr":
{"$ne":
[{"$filter":
{"input": "$expenses",
"cond":
{"$and":
[{"$eq": ["$$this.name", "electricity"]},
{"$ne": ["$$this.assigned", "$$this.given"]}]}}}, []]}}}])
Upvotes: 1