简体   繁体   中英

Mongodb find query array starts with element

I have collection where document like:

{ "_id" : 1, "path" : [ 3, 1 ], "name" : "A" }
{ "_id" : 2, "path" : [ 3, 1, 1 ], "name" : "B" }
{ "_id" : 3, "path" : [ 3, 1, 1, 1 ], "name" : "C" }
{ "_id" : 4, "path" : [ 3, 1, 2 ], "name" : "D" }
{ "_id" : 5, "path" : [ 3, 1, 2, 1 ], "name" : "E" }
{ "_id" : 6, "path" : [ 3, 1, 3 ], "name" : "F" }
{ "_id" : 7, "path" : [ 3, 2 ], "name" : "G" }
{ "_id" : 8, "path" : [ 3, 2,1 ], "name" : "H" }

Now I'm trying to query which all path starts with 3,1:

db.exp3.find({"path": {"$elemMatch": {"0": 3}}});

not working .

Any hints?

您可以按如下方式查询:

db.myObject.find({"path.0" : 3, "path.1" : 1})

Alternatively if you can store path as a string, then you can index it and a starts with query can you use an anchored query to make it use the index. eg

db.so.insert({ "_id" : 1, "path" : "3/1", "name" : "A" })
db.so.insert({ "_id" : 2, "path" : "3/1/1", "name" : "B" })
....
db.so.ensureIndex({path:1})
db.so.find({path:/^3\/1/})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM