I am trying to query mongodb using spring. We have a collection which holds a tree and a include a list of items as a tree path (so we can easily traverse the tree). We have a query which needs to return all child nodes of a specific node. Our query is based on selecting all nodes that have the node (parent) in the path and are one level lower than the parent (level). Our criteria is as follows:
Criteria.where("treePath").in(parentId).and("treePath").size(level)
Alas, when we call this on mongodb we get the following exception:
org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDBObject, you can't add a second 'treePath' expression specified as 'treePath : { "$size" : 2}'. Criteria already contains 'treePath : { "$in" : [ "50137df5f49f9b4a6481d639"]}'.
Are there other suggestions on how to achieve the same? One option I was thinking of was to query mongodb directly. I tried
String command = "{findAndModify:\"Task\",query:{$and:[{treePath:\"5013a79a36600872ecf4dba8\"},{treePath:{$size:2}},{order:{$gte:0}}]},update:{$inc:{order:1}}}";
CommandResult commandResult = mongoTemplate.executeCommand(command);
But this will only update the first record and I need them all updated.
Thanks!
This will do what you want:
int parentId = 100;
int level = 5;
Criteria c = new Criteria().andOperator(Criteria.where("treePath").is(parentId),
Criteria.where("treePath").size(level));
System.out.println(c.getCriteriaObject());
It prints
{ "$and" : [ { "treePath" : 100} , { "treePath" : { "$size" : 5}}]}