在我使用MongoDB時,我開始理解MongoDB索引的問題。問題是MongoDB索引有時不會強制查詢兩端邊界。下面是在查詢的數據庫中,我遇到了一個輸出:MongoDB索引邊界約束
查詢:
db.user.find({transaction:{$elemMatch:{product:"mobile", firstTransaction:{$gte:ISODate("2015-01-01"), $lt:ISODate("2015-01-02")}}}}).hint("transaction.product_1_transaction.firstTransaction_1").explain()
輸出:
"cursor" : "BtreeCursor transaction.firstTransaction_1_transaction.product_1",
"isMultiKey" : true,
"n" : 622,
"nscannedObjects" : 350931,
"nscanned" : 6188185,
"nscannedObjectsAllPlans" : 350931,
"nscannedAllPlans" : 6188185,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 235851,
"nChunkSkips" : 0,
"millis" : 407579,
"indexBounds" : {
"transaction.firstTransaction" : [
[
true,
ISODate("2015-01-02T00:00:00Z")
]
],
"transaction.product" : [
[
"mobile",
"mobile"
]
]
},
正如你可以看到在上面的例子爲firstTransaction場一個綁定的末端真實而不是我提到的日期。我發現解決方法是min(),max()函數。我試過這些,但他們似乎沒有使用嵌入式文檔(事務是一個包含firstTransaction,產品等字段的子文檔數組)。我收到以下錯誤:
查詢:
db.user.find({transaction:{$elemMatch:{product:'mobile'}}}).min({transaction:{$elemMatch:{firstTransaction:ISODate("2015-01-01")}}}).max({transaction:{$elemMatch:{firstTransaction:ISODate("2015-01-02")}}})
輸出:
planner returned error: unable to find relevant index for max/min query
firstTransaction字段建立索引,雖然還有產品&其複合索引了。我不知道這裏出了什麼問題。
樣品文件:
{
_id: UUID (indexed by default),
name: string,
dob: ISODate,
addr: string,
createdAt: ISODate (indexed),
.
.
.,
transaction:[
{
firstTransaction: ISODate(indexed),
lastTransaction: ISODate(indexed),
amount: float,
product: string (indexed),
.
.
.
},...
],
other sub documents...
}
這將是相當有益的看到你的查詢,而不僅僅是'explain'的輸出...... – mnemosyn 2015-02-09 09:52:13