Java中的MongoDB查询,在嵌套对象中搜索/查找 [英] MongoDB Query in Java, search/find in nested object

查看:1319
本文介绍了Java中的MongoDB查询,在嵌套对象中搜索/查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB上使用Java进行查询时遇到了一些麻烦.

I'm having a little trouble with a query in Java on a MongoDB.

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

I have the follow structure in the database:

            {
              "_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'

I want the query the database for the field 'Status.name', example SELECT * FROM table WHERE status.name = 'Expired'

我将如何在Java中对MongoDB进行这样的查询?

How would I do such a query in Java for 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查询,在嵌套对象中搜索/查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆