[英]How can I find a document in an array with MongoDB API Java?
Here's my code 这是我的代码
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();
}
And here is how my collection looks: 这是我的收藏集的外观:
{
"_id" : ObjectId("560b8b76a37991ab2d650ca9"),
"users" : [
{
"firstname" : "Marc",
"lastname" : "Berger",
"email" : "marc@berger.com",
"phone" : "12345"
},
{
"firstname" : "Arnold",
"lastname" : "Schwarzenegger",
"email" : "pumping@iron.com",
"phone" : "12345"
}]
}
I bassically want to get the document in users where the email is equal marc@berger.com, but it returns the whole document with the array as one. 我非常想在电子邮件等于marc@berger.com的用户中获取该文档,但是它将整个文档与数组一起返回。 I think the problem is the first parameter in the eq method but I can't find a solution on google how make that statement.
我认为问题是eq方法中的第一个参数,但我无法在google上找到解决方案,即如何制作该语句。
You use the positional $
operator in projection in order to return only the matched element of the array. 您可以在投影中使用位置
$
运算符,以便仅返回数组中匹配的元素。 This uses the .projection()
method upon .find()
with the MongoDB 3.x java driver: 它使用MongoDB 3.x Java驱动程序对
.find()
使用.projection()
方法:
MongoCursor<Document> f = coll.find(eq("users.email", "marc@berger.com"))
.projection(new Document("users.$",1)).iterator();
Then all results will only return the matched array element rather than all array elements. 然后,所有结果将仅返回匹配的数组元素,而不是所有数组元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.