問題描述
優化 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 完全以這種方式工作。
參考解法
方法 1:
If there are no indexes we have to scan the full collection (collection scan) in order to find the required documents. In your case if you want to apply with order [department, floor and sex] you should create this compound index:
db.employees.createIndex( { "department": 1, "floor": 1, "sex" : 1 } )
As documentation: 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.
(by Rachit Agrawal、zeugor)