在Mongodb中获取多个值的不同值 [英] Getting Distinct values of multiple values in Mongodb

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

问题描述

让我们想象一下我有以下几本书(为简洁起见,编辑了ID字段):

Let's imagine I have the following collection of books (Edited out the ID field for compactness):

{ "author" : "Steve Jones", "title" : "Fun Stuff",    "edition" : "2010" }
{ "author" : "Steve Jones", "title" : "Fun Stuff",    "edition" : "2011" }
{ "author" : "Steve Jones", "title" : "Boring Stuff", "edition" : "2010" }
{ "author" : "Ben Johnson", "title" : "Other Stuff",  "edition" : "2010" }

我应该只查找每本书的最新版本,该怎么办?换句话说:我想得到一个结果,该结果省略了史蒂夫·琼斯(Steve Jones)的 Fun Stuff 的2010年版本,而只包含2011年的版本:

What should I do I want to find only the latest edition of each book? In other words: I want to get a result which omits the 2010 edition of Steve Jones' Fun Stuff, and only has the 2011 edition:

{ "author" : "Steve Jones", "title" : "Fun Stuff",    "edition" : "2011" }
{ "author" : "Steve Jones", "title" : "Boring Stuff", "edition" : "2010" }
{ "author" : "Ben Johnson", "title" : "Other Stuff",  "edition" : "2010" }

如果这是一个关系数据库,而我正在编写查询,我可能会写类似 SELECT DISTINCT标题,DISTINCT作者,WHERE 1 SORT BY版本DESC 之类的东西.因此,我来​​自SQL背景的本能是查找 db.collection.distinct(),但它的工作方式与我以前的工作方式大不相同;它只会返回一个数组,该数组具有单个字段的每个不同值.

If this was a relational database and I were writing a query, I'd probably write something like SELECT DISTINCT title, DISTINCT author, edition WHERE 1 SORT BY edition DESC. So my instinct coming from a SQL background is to look up db.collection.distinct() but it seems to work pretty differently than what I'm used to; it only returns an array with each distinct value for that a single field.

这是我需要以编程方式解决的问题吗?还是我可以完全使用mongo函数和bson做到这一点?

Is this something that I would need to tackle programmatically? Or can I do this entirely with mongo functions and bson?

推荐答案

尝试执行以下操作:

db.textbooks.aggregate({ $group: {
    _id: { title: "$title", author: "$author" },
    latestEdition: { $max: "$edition" }
}})

这将按书名和标题为您提供每本独特的书作者和最新版本.使用查询和聚合来获得所需的确切信息.

That will give you each unique book by title & author and the latest edition. Play around with the query and aggregation to get exactly what you want.

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

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