优化 mongodb 中的查询

Optimising queries in mongodb

我正在努力优化我在 mongodb 中的查询。

在正常的 sql 查询中,有一个应用 where 子句的顺序。例如select * from employees where department="dept1" and floor=2 and sex="male",这里首先应用 department="dept1",然后应用 floor=2,最后应用 sex="male"

我想知道它在 mongodb 中是否以类似的方式发生。 例如。 DbObject search = new BasicDbObject("department", "dept1").put("floor",2).put("sex", "male"); 此处将首先应用哪个匹配子句,否则 mongo 完全以这种方式工作。

这个问题基本上源于我在 SQL 数据库方面的背景。

请帮忙。

如果没有索引,我们必须扫描整个集合(集合扫描)以找到所需的文件。在你的情况下,如果你想申请 [department, floor and sex] 你应该创建这个复合索引:

db.employees.createIndex( { "department": 1, "floor": 1, "sex" : 1 } )

作为文档:https://docs.mongodb.org/manual/core/index-compound/

db.products.createIndex( { "item": 1, "stock": 1 } )

The order of the fields in a compound index is very important. In the previous example, the index will contain references to documents sorted first by the values of the item field and, within each value of the item field, sorted by values of the stock field.