MongoDB:如何计算密钥中的值的数量



我是MongoDB的新手,我需要帮助了解如何在MongoDB中对密钥执行聚合,并使用该结果返回匹配项。

例如,如果我有一个名为Fruits的集合,其中包含以下文档:

{
"id": 1,
"name": "apple",
"type": [
"Granny smith",
"Fuji"
]
}, {
"id": 2,
"name": "grape",
"type": [
"green",
"black"
]
}, {
"id": 3,
"name": "orange",
"type": [
"navel"
]
}

如何编写一个查询,返回两种水果的名称,即苹果和葡萄?

谢谢!

演示-https://mongoplayground.net/p/ke3VJIErhvb

使用$size获取具有2个类型的记录

https://docs.mongodb.com/manual/reference/method/db.collection.find/#mongodb-方法-db.collection.find

$size运算符将任何数组与参数指定的元素数相匹配。例如:

db.collection.find({
type: { "$size": 2 } // match document with type having size 2
},
{ name: 1 } // projection to get name and _id only  
)

要获得数组的长度,应在$project管道阶段中使用$size运算符

所以管道$项目阶段应该看起来像这个

{
"$project": {
"name": "$name",
type: {
"$size": "$type"
}
}
}

以下是一个相同的工作示例⇒https://mongoplayground.net/p/BmS9BGhqsFg

最新更新