How can I execute a query in MongoDB that returns _id if FirstArray
and SecondArray
has elements in common in "Name" field?
This is the collection structure:
{
"_id" : ObjectId("58b8d9e3b2b4e07bff8feed5"),
"FirstArray" : [
{
"Name" : "A",
"Something" : "200 ",
},
{
"Name" : "GF",
"Something" : "100 ",
}
],
"SecondArray" : [
{
"Name" : "BC",
"Something" : "200 ",
},
{
"Name" : "A",
"Something" : "100 ",
}
]
}
3.6 Update:
Use $match
with $expr
. $expr
allows use of aggregation expressions inside $match
stage.
db.collection.aggregate([
{"$match":{
"$expr":{
"$eq":[
{"$size":{"$setIntersection":["$FirstArray.Name","$SecondArray.Name"]}},
0
]
}
}},
{"$project":{"_id":1}}
])
Old version:
You can try $redact
with $setIntersection
for your query.
$setIntersection
to compare the FirstArray
s Name
s with SecondArray
s Name
s and return array of common names documents followed by $size
and $redact
and compare result with 0
to keep and else remove the document.
db.collection.aggregate(
[{
$redact: {
$cond: {
if: {
$eq: [{
$size: {
$setIntersection: ["$FirstArray.Name", "$SecondArray.Name"]
}
}, 0]
},
then: "$$KEEP",
else: "$$PRUNE"
}
}
}, {
$project: {
_id: 1
}
}]
)
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