gpt4 book ai didi

java - Java中的MongoDB查询,在嵌套对象中搜索/查找

转载 作者:可可西里 更新时间:2023-11-01 09:18:25 25 4
gpt4 key购买 nike

我在 MongoDB 上使用 Java 进行查询时遇到了一些问题。

我在数据库中有以下结构:

            {
"_id" : ObjectId("5059c214707747cbc5819f6f"),
"id" : "7",
"title" : "test4",
"keywords" : "keyword 1, keyword 2",

"partner" : {
"id" : "1",
"name" : "partner",
"keywords" : "partner keyword 1, partner keyword 2"
},
"status" : {
"id" : "0",
"name" : "Expired"
},

"modified" : "2012-09-27"
}

我想查询数据库中的“Status.name”字段,例如SELECT * FROM table WHERE status.name = 'Expired'

我如何在 Java 中为 MongoDB 执行这样的查询?

感谢任何帮助或建议!

最佳答案

这是一个例子:

import com.mongodb.Mongo;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DB;

public class MongoTest {

public static void main(String[] args) throws Exception {

// connect to the local database server
Mongo m = new Mongo();

DB db = m.getDB( "test" );

DBCollection coll = db.getCollection("test");

// delete all the data from the 'test' collection
coll.drop();

// make a document
BasicDBObject doc = new BasicDBObject();

doc.put("id", 7);
doc.put("title", "test4");
doc.put("modified", "2012-09-27");

BasicDBObject status = new BasicDBObject();

status.put("id", "1");
status.put("name", "Expired");

doc.put("status", status);

// insert
coll.insert(doc);

BasicDBObject query = new BasicDBObject("status.name", "Expired");

// run the query and print the results out
DBCursor cursor = coll.find(query);

try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

m.close();
}
}

关于java - Java中的MongoDB查询,在嵌套对象中搜索/查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670195/

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