在Mongodb中获取多个值的不同值

编程入门 行业动态 更新时间:2024-10-23 22:22:50
本文介绍了在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中获取多个值的不同值

本文发布于:2023-11-22 18:38:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618551.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!