2015-10-01 47 views
0

这里是我的代码如何使用MongoDB API Java在数组中找到文档?

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", "[email protected]")).iterator(); 
try { 
while (f.hasNext()) { 
    System.out.println("Mongo Cursor: " +f.next().toJson()); 
} 
} finally { 
    f.close(); 
} 

这里是我收集的外观:

{ 
"_id" : ObjectId("560b8b76a37991ab2d650ca9"), 
"users" : [ 
    { 
     "firstname" : "Marc", 
     "lastname" : "Berger", 
     "email" : "[email protected]", 
     "phone" : "12345" 
    }, 
    { 
     "firstname" : "Arnold", 
     "lastname" : "Schwarzenegger", 
     "email" : "[email protected]", 
     "phone" : "12345" 
    }] 
} 

我bassically想在电子邮件等于[email protected]用户的文件,但它返回整个文档与数组为一体。我认为问题是eq方法中的第一个参数,但我无法在google上找到解决方案。

+2

[只检索MongoDB集合中的对象数组中的查询元素]可能的副本(http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array -in-mongodb-collection)这是一个常见的问题,在这里解释了很多可能的解决方案。在你的情况下,基本的意思是在投影中使用位置'$'操作符。 –

+0

我认为他们正在使用'BasicDBObject',如果您使用'.getDB()'方法,则会使用该方法,但不推荐使用此方法,因此我必须使用返回MongoDatabase的'.getDatabase()'。 – marcmaann

+0

位置'$'操作符与任何弃用的操作无关,因为它是一个基本构造。在投影中,这告诉MongoDB只返回数组的第一个匹配元素。其他解决方案有多种聚合用途来返回“多个”匹配。查找在查询中使用“投影”字段。这些解决方案扩展了所有的语言和驱动程序,因为这只是MongoDB的基本方式。 –

回答

1

您在投影中使用positional $运算符以仅返回数组的匹配元素。这在.find()与MongoDB的3.x的java的驱动程序使用.projection()方法:

MongoCursor<Document> f = coll.find(eq("users.email", "[email protected]")) 
    .projection(new Document("users.$",1)).iterator(); 

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

相关问题