MongoDB: find document matching a condition in all of its subdocument
I am trying to write a mongo query to get a result that satisfies the condition for its entire nested document,
1. {
"_id" : 1,
"data" : [
{
"Id" : "513",
"Nom" : "alouale pfouga",
}
],
"campaigns" : [
{
"user" : "1",
"latest" : NumberInt(0),
"postcode" : [
[
]
],
},
{
"user" : "2",
"latest" : NumberInt(1),
"postcode" : [
{
"id" : "772",
"name" : "xxx",
}
],
}
],
}
2. {
"_id" : 2,
"data" : [
{
"Id" : "514",
"Nom" : "pfouga remi",
}
],
"campaigns" : [
{
"user" : "1",
"latest" : NumberInt(0),
"postcode" : [
[
]
],
},
],
}
I need to find a record where the Zip code array is empty. As far as I understand, the request is like this: db.users.find({"campaigns.postcode":[]})
gives me both records, but I only need it record 2
because it record 1
has a zip node in one subdock, please help me !!!
source to share
This will give you the answer:
db.test.find({ 'campaigns.postcode': { $size: 0 } } )
but in your case 'campaigns.postcode'
has an empty array which means the size is not 0, its 1
You have to delete empty array
"postcode" : [
[
]
],
it should be
"postcode" : []
Updated: After spending some time asking the question I figured out the problem
To convert "postcode" : [[]]
to, "postcode" : []
you can use this code:
db.test.find({ 'campaigns.postcode': []} ).forEach(function(item){
for(var i0 = 0; i0 < item.campaigns.length; i0++)
{
if(item.campaigns[i0].postcode[0].length == []) item.campaigns[i0].postcode = [];
}
db.test.update({'_id' : item._id}, item);
});
after that you can find your correct result:
db.test.find({ 'campaigns.postcode': { $size: 0 }, 'campaigns': { $size: 1 } } )
source to share
In your json structure, it contains
"postcode" : [
[
]
],
So, I tried some but didn't find any exact results in the expected results. I found zip data where all zip was empty using the following aggregation
db.collectionName.aggregate({"$unwind":"$campaigns"},
{"$unwind":"$campaigns.postcode"},
{"$match":{"campaigns.postcode":{"$size":0}}})
source to share