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

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

}

我想在数据库中查询字段’Sta​​tus.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中的MongoDB查询,在嵌套对象中搜索/查找 的全部内容, 来源链接: utcz.com/qa/416614.html

回到顶部