0

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/

HeWhoBuilds
  • 97
  • 1
  • 13

1 Answers1

1

/../ 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?

Community
  • 1
  • 1
Derick
  • 35,169
  • 5
  • 76
  • 99
  • You and @Abhishek Kumar were very close. I did indeed have to turn into a pattern but no need to put the comas and slashes: query.put("path", Pattern.compile(array[i])); This worked fine, thank you for the help. – HeWhoBuilds Jun 23 '13 at 14:53
  • You'd need the comma's if you want to make sure it matches to only parts, otherwise compile("c") would also match against "abcdef" and not just "b,c,d". I suggest you always have a , on either side of your path string elements. – Derick Jun 23 '13 at 15:14