如何使用java驱动程序将文档与mongodb中的现有数组元素进行匹配

时间:2015-08-13 05:50:40

标签: java mongodb mongodb-query

大家好我想尝试使用mongodb java驱动程序匹配文档,例如:

     {
             "fName" : "abc",
             "lName" : "456",
             "dob" : "00",
             "address" : "xyz"
     }

"nameIdentity" : [
     {
             "fName" : "abc",
             "lName" : "def",
             "dob" : "00",
             "address" : "xyz"
     },
     {
             "fName" : "123",
             "lName" : "456",
             "dob" : "00",
             "address" : "789"
     }

如果我找到该文件,那么我就不做任何其他事情添加文件。我的问题是如果我的源文档包含fname:abc和lname:456这是第一组nameIdentity中的fname和第二组标识中的lname匹配。我希望这是一个完整的匹配。我尝试过这样的事情

List<Document> nameIdentities = (List<Document>) matchedDocument.get("nameIdentity");
for (int i=0;i<nameIdentities.size();i++)
{
    temp.add(nameIdentities.get(0));
    quBasicDBObject=new BasicDBObject("$and",temp);

}

iterable = mongoDatabase.getCollection("entity").find(updatedDocumentTypeOne);

if (iterable.first() == null)
{
    updateResult = mongoDatabase.getCollection("entity")
                .updateOne(
                    new Document("_id", new ObjectId(objectId)),
                    new Document("$push", new Document("nameIdentity", nameList.get(0))));
                                }

任何建议我哪里出错?

1 个答案:

答案 0 :(得分:1)

<强>更新 您可能必须使用聚合框架。

可能是这样的:

List<Bson> filterList = new ArrayList<>();
filterList.add(new BsonDocument().append("nameIdentity.fName", new BsonString("abc") ));
filterList.add(new BsonDocument().append("nameIdentity.lName", new BsonString("456") ));

FindIterable<org.bson.Document> it = collection.find(Filters.and(filterList));