dot*_*ezz 4 mongodb bson mongodb-query
我要为标题道歉; 我意识到这不是很具描述性.希望问题机构会更好!
让我们想象一下,我有以下书籍集(编辑出紧凑的ID字段):
{ "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" }
Run Code Online (Sandbox Code Playgroud)
我该怎么办?我只想找到每本书的最新版本?换句话说:我希望得到一个结果,这个结果省略了2010年史蒂夫琼斯的趣味东西,并且只有2011版:
{ "author" : "Steve Jones", "title" : "Fun Stuff", "edition" : "2011" }
{ "author" : "Steve Jones", "title" : "Boring Stuff", "edition" : "2010" }
{ "author" : "Ben Johnson", "title" : "Other Stuff", "edition" : "2010" }
Run Code Online (Sandbox Code Playgroud)
如果这是一个关系数据库,我正在编写一个查询,我可能会写一些类似的东西SELECT DISTINCT title, DISTINCT author, edition WHERE 1 SORT BY edition DESC.所以我来自SQL背景的本能是查找db.collection.distinct(),但它似乎与我以前的工作方式完全不同; 它只返回一个数组,其中包含单个字段的每个不同值.
这是我需要以编程方式解决的问题吗?或者我可以完全使用mongo函数和bson吗?
尝试这样的事情开始:
db.textbooks.aggregate({ $group: {
_id: { title: "$title", author: "$author" },
latestEdition: { $max: "$edition" }
}})
Run Code Online (Sandbox Code Playgroud)
这将按标题和作者以及最新版本为您提供每本独特的书籍.使用查询和聚合来获得您想要的内容.