Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用MongoDB API Java在数组中查找文档?_Java_Mongodb_Mongodb Query - Fatal编程技术网

如何使用MongoDB API Java在数组中查找文档?

如何使用MongoDB API Java在数组中查找文档?,java,mongodb,mongodb-query,Java,Mongodb,Mongodb Query,这是我的密码 ServerAddress sa = new ServerAddress("localhost", 27017); MongoClient mongoClient = new MongoClient(sa); MongoDatabase db = mongoClient.getDatabase("waitinglist"); MongoCollection<Document> coll = db.getCollection("users"); MongoCursor&l

这是我的密码

ServerAddress sa = new ServerAddress("localhost", 27017);
MongoClient mongoClient = new MongoClient(sa);
MongoDatabase db = mongoClient.getDatabase("waitinglist");
MongoCollection<Document> coll = db.getCollection("users");
MongoCursor<Document> f = coll.find(eq("users.email", "marc@berger.com")).iterator();
try {
while (f.hasNext()) {
    System.out.println("Mongo Cursor: " +f.next().toJson());
}
} finally {
  f.close();
}
我基本上希望在电子邮件相同的用户中获取文档marc@berger.com,但它返回整个文档,并将数组作为一个数组返回。我认为问题是eq方法中的第一个参数,但我在google上找不到一个解决方案。在投影中使用运算符只返回数组中匹配的元素。在MongoDB 3.x java驱动程序中使用
.find()
时的
.projection()
方法:

MongoCursor<Document> f = coll.find(eq("users.email", "marc@berger.com"))
    .projection(new Document("users.$",1)).iterator();
MongoCursor f=coll.find(eq(“users.email”),“marc@berger.com"))
.projection(新文档(“users.$”,1)).iterator();

然后,所有结果将只返回匹配的数组元素,而不是所有数组元素。

它的可能重复是一个常见问题,这里解释了许多可能的解决方案。在您的例子中,基本的方法是指在投影中使用位置的
$
操作符。我认为它们使用的是
BasicDBObject
,如果您使用“.getDB()”方法,则会使用该方法,但该方法已被弃用,因此我必须使用“.getDatabase())'返回一个MongoDatabase。位置
$
运算符与任何不推荐的对象无关,因为它是一个基本构造。在投影中,这告诉MongoDB只返回数组的第一个匹配元素。还有一些解决方案多次使用聚合来返回“多个”匹配。在查询中查找是否使用字段的“投影”。解决方案可以扩展到所有语言和驱动程序,因为这只是MongoDB的基本方式。好的,我理解,但我仍然不知道如何将find命令组合在一起。
MongoCursor<Document> f = coll.find(eq("users.email", "marc@berger.com"))
    .projection(new Document("users.$",1)).iterator();