查询MongoDB中的内部数组大小 [英] Querying internal array size in MongoDB

查看:48
本文介绍了查询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版)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆