在MongoDB中检索列表的长度 [英] Retrieving the length of a list in MongoDB

查看:788
本文介绍了在MongoDB中检索列表的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行mongo查询,以获取每个文档中数组的长度,而不检索列表的全部内容.理想情况下,这是沿着以下方向的投影选项:

I'm trying to do a mongo query where I get the length of an array in each document, without retrieving the full contents of the list. Ideally, this would be a projection option along these lines:

db.log.find({},{entries:{$length: 1}})

,但不支持此功能.借助新的聚合框架,也许可以用一种优雅的方式做到这一点?我想出的是这样的:

but this isn't supported. Maybe this is possible in an elegant way with the new aggregation framework? What I've come up with is this:

db.log.find({},{"entries.length": 1})

返回的结果如下:

{ "_id" : ObjectId("50d2fb07e64cfa55431de693"), "entries" : [   {    },     {    },     {    },     {    },     {    },     {    },     {    },     {  },   {    },     {    },     {    },     {    },     {    },     {  },   {    },     {    },     {    },     {    } ] }

这很丑陋,但基本上可以满足我的需求,因为我可以计算此列表的长度,而不必担心获得全部内容的网络负担.但是我不知道为什么会这样.该查询实际上在做什么?

This is ugly but basically serves my needs since I can count the length of this list without the network weight of getting the full contents. But I have no idea why this works. What is this query actually doing?

推荐答案

现在,我可以考虑两种方法:

Now, I could think in two approachs:

1)使用聚合框架:

db.log.aggregate([ { $unwind : "$entries" }, { $group : { _id : "$_id", entries : {$sum:1}  } }  ]);

2)或者,您可以在文档中添加一个字段以保存条目数.因此,每次将新值推送到entrys数组时,都必须增加计数器.更新将是这样的:

2) Or you can add a field to the document that holds the entries count. So, each time that you push a new value to entries array, you must increment the counter. The update will be like this:

db.log.update({ _id : 123 }, { $push : { entries : 'value' }, $inc : { entriesCount : 1 } })

很显然,您需要在此进行权衡:对于此简单操作,聚合框架过于昂贵.但是在文档中添加一个字段后,每次更新都应增加计数器.

Clearly, you have a trade-off here: the aggregation framework is too expensive for this simple operation. But adding a field to document, every update should increment the counter.

恕我直言,该计数器看起来更合理,尽管它是一种解决方法.

IMHO, the counter looks more reasonable, though it looks a workaround.

这篇关于在MongoDB中检索列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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