如何使用Java驱动程序在MongoDB中将文档与现有数组元素匹配

4

大家好,我正在尝试使用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))));
                                }

你有什么建议,我做错了什么吗?


不,我看到了上面的链接。我相信我的问题是不同的。 - Shaik Mujahid Ali
只是想澄清您的意图。您是想避免在另一个数组元素中匹配“fname”或“lname”属性时推送新的数组元素吗?还是您只是寻找单个唯一属性,例如“fname”不存在于任何数组元素中?那么期望的响应是什么?报告未修改内容,还是其他内容? - Blakes Seven
1个回答

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));

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