【问题标题】:mongodb aggregation and sorting on moongoose schemamongoose模式中的mongodb聚合和排序
【发布时间】:2017-04-10 03:52:06
【问题描述】:

有两种猫鼬模式

    const bookModel =  new Schema({
    title : String,
    content: String,
    author:{
        id:{
            type: ObjectId,
        },
        name:{
            type: String,
        }
    }
})


const commentModel = new Schema({
    text :String,
    bookid :{ { type : ObjectId , required : true } },
    inEnglish:{
        type: Boolean,
        default:false
    }
})

我们如何编写一个 mongo 查询来根据 cmets 的数量查找名著

因此,编写查找查询以根据特定书籍上的 cmets 数量(其中 inEnglish 设置为 true)对书籍进行排序。

JSON 在 mongo 中存储为:

预订 JSON-

{
    "_id" :ObjectId(58368df330391521247f6aeb),
    "title": "Dan Brown",
    "content": "COntent of the book" 
}

评论 JSON-

{
        "_id" :ObjectId(24568df330391765434f6fgh),
        "text":"Nice Book",
        "bookid":"58368df330391521247f6aeb",
        inEnglish: true

}

【问题讨论】:

  • 您写过任何查询吗?我的意思是你有没有尝试过一些东西并卡在某个地方?
  • db.comments.aggregate( { $match : { inEnglish : true} }, {$group : { _id: {bookId :"$bookId"}, "totalC":{$sum:1}}}, {$sort : {"_id.totalC":1}}) 我已经尝试过了,但它不起作用

标签: mongodb mongoose mongodb-query mongoose-schema


【解决方案1】:

我创建了一个小集合

>db.comments.find()

{"_id" : ObjectId("58387da2a32c4b96e67ec6b4"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387da8a32c4b96e67ec6b5"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387da9a32c4b96e67ec6b6"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387da9a32c4b96e67ec6b7"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aeb", "inEnglish" : true }
{"_id" : ObjectId("58387db0a32c4b96e67ec6b8"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aec", "inEnglish" : true }
{"_id" : ObjectId("58387db2a32c4b96e67ec6b9"), "text" : "Nice Book", "bookid" : "58368df330391521247f6aec", "inEnglish" : true }

现在要预订 cmets,我运行以下命令

db.comments.aggregate(
    {$group : {_id : "$bookid", "count" : {$sum : 1}}},
    {$sort : {"count" : -1}},
    {$limit : 1}
)

基本上我正在做的是按书籍 ID 分组并获取计数。

我的输出

{ "_id" : "58368df330391521247f6aeb", "count" : 4 }

注意:我没有使用 inEnglish:true 进行过滤。如果您愿意,可以将其包含在查询中,

【讨论】:

  • 通过上面的查询,你将只能找到书的ID。尝试此查询以获取书籍 db.getCollection('cmets').aggregate([ {$group : {_id : "$bookid", "count" : {$sum : 1}}}, {$排序:{“count”:-1}},{$limit:1},{ $lookup:{ from:“books”,localField:“_id”,foreignField:“_id”,as:“books”}}] )
  • 你指的是我给的那个还是Anish给的那个?
猜你喜欢
  • 2017-01-05
  • 1970-01-01
  • 2015-03-29
  • 2016-11-17
  • 2020-04-23
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
相关资源
最近更新 更多