在 MongoDB 中查询内部数组大小 [英] Querying internal array size in MongoDB
本文介绍了在 MongoDB 中查询内部数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑 users
集合中的 MongoDB 文档:
Consider a MongoDB document in users
collection:
{ username : 'Alex', tags: ['C#', 'Java', 'C++'] }
有什么方法可以从服务器端获取 tags
数组的长度(不将标签传递给客户端)?
Is there any way, to get the length of the tags
array from the server side (without passing the tags to the client) ?
谢谢!
推荐答案
现在 MongoDB(2.6 版本)支持 $size
聚合操作.
Now MongoDB (2.6 release) supports $size
operation in aggregation.
来自文档:
{ <field>: { $size: <array> } }
您可以使用以下任一方法完成您想要的:
What you want can be accomplished as following with either by using this:
db.users.aggregate(
[
{
$group: {
_id: "$username",
tags_count: {$first: {$size: "$tags" }}
}
}
]
)
或
db.users.aggregate(
[
{
$project: {
tags_count: {$size: "$tags"}
}
}
]
)
这篇关于在 MongoDB 中查询内部数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文