我正在收集下面的结构。这里有一些重复的内容标题名称和值。但我需要获取确切的文档。
{
"_id": ObjectId("573ebc7bbf50112d55c0b763"),
"topic": "AAA",
"contents": [{
"headerName": "Start Year",
"value": 1995
}, {
"headerName": "Program",
"value": "AAA"
}]
}, {
"_id": ObjectId("573ebc7bbf50112d55c0b763"),
"topic": "BBB",
"contents": [{
"headerName": "Start Year",
"value": 1989
}, {
"headerName": "Program",
"value": "BBB"
}, {
"headerName": "Likes",
"value": 51
}]
}, {
"_id": ObjectId("573ebc7bbf50112d55c0b763"),
"topic": "BBB",
"contents": [{
"headerName": "Start Year",
"value": 1989
}, {
"headerName": "Program",
"value": "BBB"
}]
}
我需要使用以下查询获取单个文档。我该如何为此添加索引。
db.collections.find({
"$and": [{
"topic": "BBB"
}, {
"contents": [{
"headerName": "Start Year",
"value": 1989
}, {
"headerName": "Program",
"value": "BBB"
}]
}, {
"contents": {
"$size": 2
}
}]
})
答案 0 :(得分:1)
在字段
上创建复合索引select g.empno, f.empno from (select e.empno from emp e
where rownum < 3 or rownum >2)f, emp g
where g.empno = f.empno
and rownum < 3
请注意,与任何数据库一样,MongoDB复合索引中的顺序很重要。如果您首先使用“主题”创建索引,Mongo可以直接跳转到带有签名主题的索引部分,然后从内容执行绑定扫描
之后将您的查询更改为:
db.collection.createIndex( { topic:1, contents: 1 } )
<强>输出强>:
db.collection.find({
"topic" : "BBB",
"contents.headerName": { "$in": [ "Start Year", "Program" ] },
"contents.value": { "$in": [ 1989, "BBB" ] },
"contents": { "$size": 2 }
})
要查看索引的执行情况,请在查询中运行 explain()
:
{
"_id" : ObjectId("573ee720b986a3b71e1e517b"),
"topic" : "BBB",
"contents" : [
{
"headerName" : "Start Year",
"value" : 1989
},
{
"headerName" : "Program",
"value" : "BBB"
}
]
}
<强>输出:强>
db.collection.find({
"topic" : "BBB",
"contents.headerName": { "$in": [ "Start Year", "Program" ] },
"contents.value": { "$in": [ 1989, "BBB" ] },
"contents": { "$size": 2 }
}).explain()