【发布时间】:2014-05-10 04:19:39
【问题描述】:
我在 MongoDB 中有一个具有复杂结构和子文档的集合。 该文档的结构如下:
doc1 = {
'_id': '12345678',
'url': "http//myurl/...",
'nlp':{
"status": "OK",
"entities": {
"0": {
"type" : "Person",
"relevance": "0.877245",
"text" : "Neelie Kroes"
},
"1": {
"type": "Company",
"relevance": "0.36242",
"text": "ICANN"
},
"2": {
"type": "Company",
"relevance": "0.265175",
"text": "IANA"
}
}
}
}
doc2 = {
'_id': '987456321',
'url': "http//myurl2/...",
'nlp':{
"status": "OK",
"entities": {
"0": {
"type": "Company",
"relevance": "0.96",
"text": "ICANN"
},
"1": {
"type" : "Person",
"relevance": "0.36242",
"text" : "Neelie Kroes"
},
"2": {
"type": "Company",
"relevance": "0.265175",
"text": "IANA"
}
}
}
}
我的任务是在子文档中搜索“类型”和“文本”,然后按“相关性”排序。 使用 $elemMatch 运算符,我可以执行查询:
db.resource.find({
'nlp.entities': {
'$elemMatch': {'text': 'Neelie Kroes', 'type': 'Person'}
}
});
完美,现在我必须对所有类型为“Person”且值为“Neelie Kroes”的实体按相关性降序排序。
我尝试了正常的“排序”,但是,正如manual said 关于 $elemMatch 中的 sort(),结果可能无法反映排序顺序,因为 sort() 之前已应用于数组的元素$elemMatch 投影。
事实上,_id:987456321 将是第一个(相关性为 0.96,但参考 ICANN)。
如何按匹配的子文档的相关性对文档进行排序?
P.S.:我无法更改文档结构。
【问题讨论】:
-
这是作为某个工具的转储出来的,还是您的文档在 mongo shell 中的实际外观?我这样说是因为您将“实体”表示为“子文档”而不是数组。这些无法通过任何标准方式进行排序。
标签: mongodb sorting mongodb-query aggregation-framework