让我们想象一下我有以下几本书(为简洁起见,编辑了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中获取多个值的不同值
发布评论