通过映射集合来订购记录

时间:2015-06-18 06:54:17

标签: mongodb mongodb-query

我有2个收藏如下

作者

   {id:'1',name:'JK', bookCount:3}
   {id:'2',name:'SS', bookCount:2}
   {id:'3',name:'CC', bookCount:4}

预订 :( authorId:作者集合的外键)

   {name:'Book 1',authorId:1}
   {name:'Book 2',authorId:1}
   {name:'Book 3',authorId:1}
   {name:'Book 4',authorId:2}
   {name:'Book 5',authorId:2}
   {name:'Book 6',authorId:3}
   {name:'Book 7',authorId:3}
   {name:'Book 8',authorId:3}
   {name:'Book 9',authorId:3}

我想写一个mongo查询,它提供书籍,按 - >排序相应作者按升序编写的书籍数量,即

   {name:'Book 4',authorId:2}
   {name:'Book 5',authorId:2}
   {name:'Book 1',authorId:1}
   {name:'Book 2',authorId:1}  
   {name:'Book 3',authorId:1}
   {name:'Book 6',authorId:3}
    .......

我应该怎么做呢。 Thanx提前! :)

2 个答案:

答案 0 :(得分:1)

根据您的输出,您应该只需要聚合 Book 集合和聚合查询,如下所示:

db.book.aggregate({
  "$group": {
    "_id": "$authorId",
    "names": {
      "$push": "$name"
    },
    "count": {
      "$sum": 1
    }
  }
}, {
  "$unwind": "$names"
}, {
  "$sort": {
    "count": 1
  }
}, {
  "$project": {
    "name": "$names",
    "authorId": "$_id",
    "_id": 0
  }
})

答案 1 :(得分:0)

步骤:

1)根据authorId对您的数据进行分组并计算和         还制作一个包含该组中所有书籍的数组

2)展开书籍数组

3)根据您在分组期间创建的计数字段进行排序

4)最终以您需要的格式投影。

db.book.aggregate([
{"$group": { "_id" : "$authorId", "count": {"$sum" : 1}, 
  "arr" :   {"$push" : "$name" }}
},
{"$unwind" :"$arr"},
{"$sort":{"$count": 1 }},
{"$project": {"name" : "$arr", "authorId" : "$_id"}
}
 ]);