【问题标题】:MongoDB Tree find descendants JavaMongoDB Tree 查找后代 Java
【发布时间】:2013-06-22 20:28:24
【问题描述】:

我在 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/

【问题讨论】:

  • 试试这个:query.put("path", Pattern.compile("/,"+array[i]+",/"));

标签: java mongodb tree


【解决方案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());
}

另请参阅:How to query mongodb with “like” using the java api?

【讨论】:

  • 你和@Abhishek Kumar 非常亲近。我确实必须变成一个模式,但不需要把逗号和斜杠:query.put("path", Pattern.compile(array[i]));这很好,谢谢你的帮助。
  • 如果你想确保它只匹配部分,你需要逗号,否则 compile("c") 也会匹配 "abcdef" 而不仅仅是 "b,c,d" .我建议您始终在路径字符串元素的任一侧都有一个 , 。
猜你喜欢
  • 1970-01-01
  • 2015-09-16
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 2018-05-06
  • 1970-01-01
相关资源
最近更新 更多