mysql - 如何在 Mongodb 中获得不同的结果?

标签 mysql mongodb

我正在使用 mongoDB 2.6.5。我有一个藏书。

   > db.books.find() 

{ "_id" : "5476f8b5e4b04367d6c95010", "author" : "abc", "title" : "xyz", "isbnNo" : "9781887902991", "category" : "Computer" } 

{ "_id" : "5476fae0e4b0016adffd08e4", "author" : "bcd", "title" : "uvw", "isbnNo" : "9781887902991", "category" : "Computer" } 

{ "_id" : "5476fb7ce4b0016adffd08e5", "author" : "cde", "title" : "pqr", "isbnNo" : "9781887902991", "category" : "Biography" } 

我想要的结果是:

{ "_id" : "5476fae0e4b0016adffd08e4", "author" : "bcd", "title" : "uvw", "isbnNo" : "9781887902991", "category" : "Computer" } 

{ "_id" : "5476fb7ce4b0016adffd08e5", "author" : "cde", "title" : "pqr", "isbnNo" : "9781887902991", "category" : "Biography" } 

我指的是来自每个类别的任何一本书,例如 mySQL 中的“按类别分组”。

我怎样才能做到这一点?

提前致谢。

最佳答案

您需要将聚合管道与 $group$project 运算符一起使用。

  • 根据类别分组。
  • 选择每组中第一条记录的值。
  • 投影每组的记录。

代码:

db.books.aggregate([
{$group:{"_id":"$category",
         "author":{$first:"$author"},
         "title":{$first:"$title"},
         "isbnNo":{$first:"$isbnNo"},
         "category":{$first:"$category"}}},
{$project:{"_id":0,"author":1,
           "title":1,"isbnNo":1,"category":1}}
])

关于mysql - 如何在 Mongodb 中获得不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27242503/

相关文章:

mysql - AWS Lambda 在峰值期间淹没 RDS MySQL 连接

mongodb - Mongoose 的mapreduce函数错误

java - 需要使用 java 3.12.0 驱动程序从 java 应用程序中的 mongoDB Atlas 获取具有相同名字的客户 customerID 列表

MongoDB 和 Spark : difference between mongo-hadoop and mongo-spark

java - 在java中转换Mongodb查询

mysql - 基于另一个表更新表结构

php - 发现 PHP mySQL 语法错误

mysql - 我怎样才能得到一个列值加入相同的表值

php - 我如何在 Doctrine 2 DQL 中使用 DATE()?

node.js - 更新子文档中的数组 - mongoose mongodb