Django pymongo 搜索、排序、限制内部数组并计算它们

Django pymongo search, sort, limit on inner array and count them

我正在使用 MongoDb 学习 Django,并且有一个集合可供搜索。这是集合中的示例文档:

{ 
    "_id": {    "$oid": "62615907568ddfca4fef3a25"  }, 
    "word": 'entropy, 
    "count": 4,
    "occurrence": [
        {"book": "62615907568ddfca4fef3a23",  "year": 1942, "sentence": 0 },
        {"book": "62615907568ddfca4fef3a23",  "year": 1942, "sentence": 5 },
        {"book": "62615907568ddfca4fef3a75",  "year": 1928, "sentence": 0 },
        {"book": "62615907568ddfca4fef3a90",  "year": 1959, "sentence": 8 } 
    ]
}

我想检索特定文档(word)的'occurrence'字段的数组元素:

  1. 按年份排序
  2. 一年范围内
  3. 受偏移量限制
  4. 计算总结果(不含limit/offset)

到目前为止我所做的是:

offset= 0
limit= 10
search= {'$and': [{"_id": word_id_obj, "occurrence": {"$elemMatch": {"year": {"$gte": 1940, "$lte": 1960}}}}]}
word_docs= wordcollec.aggregate([
{"$match": search},
{"$project":
    {"occurrence":
        {"$slice": ['$occurrence', offset, limit]}
    }
},
{"$sort": {'occurrence.year': -1}}
])

# Count total results
recnt= wordcollec.aggregate([{"$match": search}, {'$group' : {"_id": "$_id", "sno" : {"$sum" : {"$size": "$occurrence"}}}}])

年份范围、计数不起作用,我无法对它们进行排序。我该如何重写我的查询?

提前致谢。

使用 $unwind 然后 $sort

db.collection.aggregate([
  {
    $match: {
      _id: { "$oid": "62615907568ddfca4fef3a25" },
      occurrence: { $elemMatch: { year: { $gte: 1940, $lte: 1960 } } }
    }
  },
  {
    $set: { totalWithoutLimitOrOffset: { $size: "$occurrence" } }
  },
  {
    $unwind: "$occurrence"
  },
  {
    $match: { "occurrence.year": { $gte: 1940, $lte: 1960 } }
  },
  {
    $sort: { "occurrence.year": -1 }
  },
  {
    $skip: 1
  },
  {
    $limit: 2
  },
  {
    $group: {
      _id: "$_id",
      word: { $first: "$word" },
      count: { $first: "$count" },
      totalWithoutLimitOrOffset: { $first: "$totalWithoutLimitOrOffset" },
      occurrence: { $push: "$occurrence" }
    }
  }
])

mongoplayground