[英]How can I check if an array of strings is empty in MongoDB with java?
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 没有地址的情况
{
"id": "12346",
"address": [""]
}
I have tried, after query the DB and get the document of the id I want, .isEmpty(), but it returns false.我试过,在查询数据库并获取我想要的 id 的文档后,.isEmpty(),但它返回 false。
Can this be done using MongoDB?这可以使用 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如果您必须处理空白地址(
"address": [""]
与"address": []
不同,而"address": null
与根本不设置address
字段不同,那么您有像这样查询L
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.我们使用
$reduce
函数来“遍历” address
数组并检查每个项目以查看它是否不是空字符串。 If not blank, we increment the $$value
field which at the end is assigned to new field X
.如果不是空白,我们增加
$$value
字段,最后分配给新字段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
.如果数组不存在或只包含空白地址(一个或多个),那么
X
将为零,我们用后续的$match
过滤掉那些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.