Mongodb查询java中的嵌套文档

时间:2015-11-02 04:42:16

标签: java mongodb

我是Mongodb的新手。我在mongodb中有以下数据集。

{
"_id": {
    "$oid": "563644f44b17ca12886440a9"
},
"data": [
    {
        "uid": 1,
        "character": " ",
        "unicode": 32,
        "color": -7309587
    },
    {
        "uid": 2,
        "character": "!",
        "unicode": 33,
        "color": -8911704
    },
    {
        "uid": 3,
        "character": "\"",
        "unicode": 34,
        "color": -1778539
    }

我正在尝试使用_id和字符从此字段中检索颜色。我无法执行查询。

这就是我的尝试。

DBObject clause1 = new BasicDBObject("_id",new ObjectId(KEY1));  
                DBObject clause2 = new BasicDBObject("data.character",text[i]);    
                BasicDBList or = new BasicDBList();
                or.add(clause1);
                or.add(clause2);
                DBObject query = new BasicDBObject("$and", or);

此外,我在寻找方法在mongodb-java中查询3.0.0+ api时遇到了很多问题。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
    MongoDatabase db = mongoClient.getDatabase("testDB");
    AggregateIterable<Document> iterable = db.getCollection("testCollection").aggregate(
            asList(new Document("$unwind", "$data"), new Document("$match", (new Document("_id", new ObjectId(
                    "5636f106b2acf98ecb033b98")).append("data.character", " "))), new Document("$project",
                    new Document("data.color", 1).append("_id", 0))));

    iterable.forEach(new Block<Document>()
    {
        @Override
        public void apply(final Document document)
        {
            System.out.println(document.toJson());
        }
    });

有关详细信息,请查看MongoDB Documentation

答案 1 :(得分:0)

一个简单的解决方案

在你的文件中, oid是每个文档的唯一键,因此您的查询应该是这样的

  DBObject query = new BasicDBObject("_id.oid", KEY1);
  // Query with value - DBObject query = new BasicDBObject("_id.oid","563644f44b17ca12886440a9");

  Assign this to a cursor as shown below
  DBCollection coll = db.getCollection("mycollection");
  DBCursor cursor = coll.find(query);
  Iterate the collection and retrieve your desired value.