2016-11-30 84 views

回答

1

這可以,如果你做正在查詢價值。但是你正在嘗試的是關鍵。我們必須對關鍵字進行精確匹配。

我們可以使用$regex匹配值而不是密鑰。

讓我們有一個集合

db.collection.find(); 
{ "_id" : ObjectId("583eed6c911c8e111fb99bf4"), "name" : "a.aa.aaa" } 
{ "_id" : ObjectId("583eed72911c8e111fb99bf5"), "name" : "a.bb.aaa" } 
{ "_id" : ObjectId("583eed77911c8e111fb99bf6"), "name" : "a.bb.bbb" } 
{ "_id" : ObjectId("583eed7b911c8e111fb99bf7"), "name" : "a.cc.bbb" } 
{ "_id" : ObjectId("583eed7f911c8e111fb99bf8"), "name" : "a.cc.aaa" } 
{ "_id" : ObjectId("583eed84911c8e111fb99bf9"), "name" : "a.cc.bbb" } 
{ "_id" : ObjectId("583eed88911c8e111fb99bfa"), "name" : "a.cc.ccc" } 
{ "_id" : ObjectId("583eed9a911c8e111fb99bfb"), "name" : "a.aa.ccc" } 
{ "_id" : ObjectId("583eeda4911c8e111fb99bfc"), "name" : "a.aa.bbb" } 
{ "_id" : ObjectId("583eedfd911c8e111fb99bfd"), "name" : "a.aa.abc" } 
{ "_id" : ObjectId("583eee03911c8e111fb99bfe"), "name" : "a.bb.abc" } 
{ "_id" : ObjectId("583eee06911c8e111fb99bff"), "name" : "a.cc.abc" } 

然後使用$正則表達式查詢就像

db.collection.find({name:{$regex: /a.*.aa*/}}); 

與此查詢的結果

{ "_id" : ObjectId("583eed6c911c8e111fb99bf4"), "name" : "a.aa.aaa" } 
{ "_id" : ObjectId("583eed72911c8e111fb99bf5"), "name" : "a.bb.aaa" } 
{ "_id" : ObjectId("583eed7f911c8e111fb99bf8"), "name" : "a.cc.aaa" } 
{ "_id" : ObjectId("583eed9a911c8e111fb99bfb"), "name" : "a.aa.ccc" } 
{ "_id" : ObjectId("583eeda4911c8e111fb99bfc"), "name" : "a.aa.bbb" } 
{ "_id" : ObjectId("583eedfd911c8e111fb99bfd"), "name" : "a.aa.abc" } 
{ "_id" : ObjectId("583eee03911c8e111fb99bfe"), "name" : "a.bb.abc" } 
{ "_id" : ObjectId("583eee06911c8e111fb99bff"), "name" : "a.cc.abc" } 

請參照:Mongodb - regex match of keys for subobjects

希望它有助於!

相關問題