MongoDB Java驱动程序3.0查询

3

你好,我正在使用 MongoDB Java 驱动程序 3.0 进行工作。我有一个类似于以下文档:

db.employee.find().pretty()

   "_id" : ObjectId("559e4ae4aed7561c94e565d5"),
   "empid" : 1,
   "name" : "abc",
   "dob" : "17/05/1990",
   "address" : [
           "559e4ae3aed7561c94e565d3",
           "559e4ae4aed7561c94e565d4"
   ]

我想查询地址字段并获取所有地址(在我的情况下是上面的那些值),而不用指定特定的值。我的代码如下:
FindIterable<Document> iterable = mongoDatabase.getCollection("employee").find(
        new Document("address", 559e4ae3aed7561c94e565d3));
iterable.forEach(new Block<Document>() {
    @Override
    public void apply(final Document document) 
        System.out.println(document);
    }
});  

我不想手动指定地址。如果我在地址上查询,我应该得到这两个值。有什么建议吗?


为什么您无法获取整个文档?这是默认情况下发生的,除非您明确要求像“仅匹配字段”这样的投影。 - Blakes Seven
1个回答

6

我们可以通过另一个已知的字段进行查询,例如:员工ID,并且只返回所需字段(在我的例子中是地址),而不是返回整个文档。

FindIterable<Document> iterable = mongoDatabase.getCollection("employee").find(
            new Document("empid", 1));
    iterable.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.get("address").toString());
        }
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接