Reputation: 97
I have a tree like this in 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" }
I would like to retrieve all descendants of b.
If I do this in the MongoDB console, I get the descendants fine:
> 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" }
but if I do this in Java:
BasicDBObject query = new BasicDBObject();
query.put("path", "/,"+array[i]+",/");
DBCursor cursor = coll.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next().toString());
}
From the debugger the query contains this: { "path" : "/,b,/"}
I get no descendants at all...Why doesn't this work?
http://docs.mongodb.org/manual/tutorial/model-tree-structures-with-materialized-paths/
Upvotes: 0
Views: 611
Reputation: 36784
/../ is special in the MongoDB shell. It is not simply a string containing a regular expression, but something that is parsed by the shell and used as a regular expression.
To do this from Java, you would do something like:
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());
}
See also: How to query mongodb with “like” using the java api?
Upvotes: 1