優化 mongodb 中的查詢 (Optimising queries in mongodb)


問題描述

優化 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 Agrawalzeugor)

參考文件

  1. Optimising queries in mongodb (CC BY‑SA 2.5/3.0/4.0)

#mongodb-java #mongoDB #query-optimization






相關問題

GridFS Java 對像是線程安全的嗎? (Are GridFS Java objects thread safe?)

Драйвер MongoDB Java: такога cmd: aggregate няма (MongoDB Java driver : no such cmd: aggregate)

Стварэнне парадкавага нумара ў mongoDB (Generating sequence number in mongoDB)

MongoDB java驅動如何判斷副本集是否處於自動故障轉移過程中? (How can MongoDB java driver determine if replica set is in the process of automatic failover?)

優化 mongodb 中的查詢 (Optimising queries in mongodb)

查詢數據時應該使用 MongoTemplate 還是 DBCollection (Should i use MongoTemplate or DBCollection when query data)

org.bson.codecs.configuration.CodecConfigurationException:找不到類 [Ljava.lang.String; 的編解碼器; (org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;)

如何使用 Java MongoDB 驅動程序檢索字段子集? (How to retrieve a subset of fields using the Java MongoDB driver?)

當使用 karras 和 clojure 給出字段時,如何更新 MongoDB 中的文檔? (How to update a Document in MongoDB when a field is given with karras & clojure?)

如何使用 java 代碼轉換 mongodb 查詢 (How to Transform mongodb query using java code)

MongoDB 文檔使用 Java 中的 findOneAndUpdate 方法更新數組元素 (MongoDB document update array element using findOneAndUpdate method in Java)

aws documentdb 是否為兩種方式的 ssl 驗證 mongodb 客戶端證書? (Does aws documentdb validate mongodb client certificate for two way ssl?)







留言討論