4

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" }

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" }

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.

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

3
  • 1
    stackoverflow.com/questions/23119692/… maybe check this for reference? Aug 25, 2015 at 2:11
  • Oh hey, look at me, asking questions that have already been answered. It's not the exact same type of question, but it had what I was looking for nonetheless. Thanks @Shih-MinLee.
    – dotVezz
    Aug 25, 2015 at 2:20
  • no prob man glad it helps Aug 25, 2015 at 2:24

1 Answer 1

7

Try something like this to start:

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.