mongodb 获取不同的记录 [英] mongodb get distinct records

查看:24
本文介绍了mongodb 获取不同的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 mongoDB,其中我收集了以下格式.

I am using mongoDB in which I have collection of following format.

{"id" : 1 , name : x  ttm : 23 , val : 5 }
{"id" : 1 , name : x  ttm : 34 , val : 1 }
{"id" : 1 , name : x  ttm : 24 , val : 2 }
{"id" : 2 , name : x  ttm : 56 , val : 3 }
{"id" : 2 , name : x  ttm : 76 , val : 3 }
{"id" : 3 , name : x  ttm : 54 , val : 7 }

在该集合中,我查询以降序获取记录,如下所示:

On that collection I have queried to get records in descending order like this:

db.foo.find({"id" : {"$in" : [1,2,3]}}).sort(ttm : -1).limit(3)

但它给出了两个相同 id = 1 的记录,我想要这样的记录,它为每个 id 提供 1 个记录.

But it gives two records of same id = 1 and I want records such that it gives 1 record per id.

在mongodb中可以吗?

Is it possible in mongodb?

推荐答案

mongodb 中有一个 distinct 命令,可以与查询结合使用.但是,我相信这只会为您命名的特定键返回一个不同的值列表(即在您的情况下,您只会得到返回的 id 值)所以我不确定这是否会为您提供您想要的需要整个文档 - 您可能需要 MapReduce.

There is a distinct command in mongodb, that can be used in conjunction with a query. However, I believe this just returns a distinct list of values for a specific key you name (i.e. in your case, you'd only get the id values returned) so I'm not sure this will give you exactly what you want if you need the whole documents - you may require MapReduce instead.

关于不同的文档:http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

这篇关于mongodb 获取不同的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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