Shaik Mujahid Ali
Shaik Mujahid Ali

Reputation: 2378

How to match a document with existing array elements in mongodb using java driver

Hello all i am trying to match a document using mongodb java driver for eg :

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

with

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

If i found the document then i don't do anything else add the document. My problem here is if my source document contains fname : abc and lname: 456 this is matching fname in the first set of nameIdentity and lname in the second set of identity. I want this to be a one complete match. I have tried something like this

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

any suggestions where am i going wrong?

Upvotes: 4

Views: 651

Answers (1)

John Manko
John Manko

Reputation: 1908

UPDATE You may have to use the aggregation framework.

Maybe something like:

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

Upvotes: 1

Related Questions