Imagine I have a DB with documents with the format:
{
"id": "12345",
"address": ["adress1","adress2","adress3"]
}
Now imagining that can be cases where one id has no addresses
{
"id": "12346",
"address": [""]
}
I have tried, after query the DB and get the document of the id I want, .isEmpty(), but it returns false.
Can this be done using MongoDB?
If you have to deal with blank addresses ( "address": [""]
is different than "address": []
which is different than "address": null
which is different than not setting the address
field at all, then you have to query like thisL
db.foo.aggregate([
{$addFields: {X: {$reduce: {
input: "$address",
initialValue: 0,
in: {$sum: [ "$$value", {"$cond":[ {"$ne": ["$$this",""]}, 1, 0]} \
]}
}}
}}
,{$match: {"X": {$gt:0} }}
]);
We use the $reduce
function to "walk" the address
array and check each item to see if it is not a blank string. If not blank, we increment the $$value
field which at the end is assigned to new field X
. If the array is not present or contains only blank addresses (one or more) then X
will be zero and we filter those out with the subsequent $match
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.