[英]How to return all documents where an array field's size is greater than a given number?
我有一个像
{
"_id": ObjectId('56a77bfae0ce9f6a738cb2b7'),
"nameIdentity": [
{
"givenNameOne": "LATANYA",
"givenNameThree": "BIZOR",
"lastName": "BIZOR",
"sourceReferenceId": [
{
"sourceReferenceId": "56a77bfae0ce9f6a738cb2b5",
"sourceName": "A"
},
{
"sourceReferenceId": "56a77bfae0ce9f6a738cb2b5",
"sourceName": "B"
}
]
}
]
}
nameIdentity 是一个数组,而 sourceReferenceId 是 nameIdentity 中的一个嵌套数组。 我正在尝试获取 sourceReferenceId 大小大于 2 的文档。我使用了这样的聚合:
db.entity.aggregate(
[
{
$project: {
nameIdentity_count: {$size: "$nameIdentity.sourceReferenceId"}
}
},
{
"$match": {
"nameIdentity_count": { "$gte": 2 }
}
}
]
)
这没有按预期工作,即使只有一个 soureReferenceId,它也会提供文档。谁能告诉我我哪里出错了?
您需要使用点符号和$exists
运算符。 如果您想要的只是find()
那些“sourceReferenceId”大小大于2
文档,那么您也不需要为此进行聚合
db.collection.find( { "nameIdentity.sourceReferenceId.2": { "$exists": true } } )
但是如果你真的需要聚合你的数据,那么:
db.collection.aggregate([
{ "$match": { "nameIdentity.sourceReferenceId.2": { "$exists": true } } }
])
你也有一个设计问题,因为有一个值总是一个元素数组的字段没有任何意义。 您应该考虑更改您的文档结构,使其看起来像这样:
{
"_id": ObjectId('56a77bfae0ce9f6a738cb2b7'),
"givenNameOne": "LATANYA",
"givenNameThree": "BIZOR",
"lastName": "BIZOR",
"sourceReferenceId": [
{
"sourceReferenceId": "56a77bfae0ce9f6a738cb2b5",
"sourceName": "A"
},
{
"sourceReferenceId": "56a77bfae0ce9f6a738cb2b5",
"sourceName": "B"
}
]
}
并根据您要执行的操作使用以下查询。
db.collection.find( { "sourceReferenceId.2": { "$exists": true } } )
或者
db.collection.aggregate([
{ "$match": { "sourceReferenceId.2": { "$exists": true } } }
])
您需要使用$size
来获取 items 数组的大小,并使用$gt
将 items 数组的大小与 0 进行比较。
db.collection.find({"items":{$gt:[{$size:"items"},0]}})
这是查询的使用方式:
db.<collection>.find( {<column> : {$exists:true}, $where:'this.<column>.length > 1'})
<collection>
: 你的收藏
<column>
: <column>
的名称
您可以将 $gt 与$size 一起使用。 返回字段“items”长度大于一的所有文档:
db.collection.find({"items": {$gt: {$size: 1}}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.