我在Mongo有一棵这样的树:
> db.data.find()
{ "_id" : "07c", "path" : null }
{ "_id" : "a", "path" : "07c,a" }
{ "_id" : "b", "data" : "{\"c\":\"olaC\",\"d\":\"olaD\"}", "path" : "07c,a,b" }
{ "_id" : "c", "c" : "{\"c\":\"olaC\",\"d\":\"olaD\"}", "path" : "07c,a,b,c" }
{ "_id" : "d", "d" : "{\"d\":\"olaD\"}", "data" : "{\"c\":\"olaC\",\"d\":\"olaD\"}", "path" : "07c,a,b,c,d" }
我想检索b。
的所有后代如果我在MongoDB控制台中执行此操作,我可以很好地了解后代:
> db.data.find({ path: /,b,/ } )
{ "_id" : "c", "c" : "{\"c\":\"olaC\",\"d\":\"olaD\"}", "path" : "07c,a,b,c" }
{ "_id" : "d", "d" : "{\"d\":\"olaD\"}", "data" : "{\"c\":\"olaC\",\"d\":\"olaD\"}", "path" : "07c,a,b,c,d" }
但如果我在Java中这样做:
BasicDBObject query = new BasicDBObject();
query.put("path", "/,"+array[i]+",/");
DBCursor cursor = coll.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next().toString());
}
在调试器中,查询包含:{“path”:“/,b,/”}
我根本没有后代......为什么这不起作用?
http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-materialized-paths/
答案 0 :(得分:1)
/../在MongoDB shell中很特别。它不仅仅是一个包含正则表达式的字符串,而是由shell解析并用作正则表达式的字符串。
要从Java执行此操作,您可以执行以下操作:
BasicDBObject query = new BasicDBObject();
query.put("name", Pattern.compile(","+array[i]+","));
DBCursor cursor = coll.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next().toString());
}