gpt4 book ai didi

java - MongoDB 树查找后代 Java

转载 作者:行者123 更新时间:2023-12-01 14:24:41 26 4
gpt4 key购买 nike

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

最佳答案

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

关于java - MongoDB 树查找后代 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17254998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com