1

Am trying to query on MongoDB collection which is like below

  {
            "_id" : ObjectId("55e9a8efc4fd0e172cbffcae"),
            "type" : "b",
            "name" : [
                    {
                            "name" : "XYZ",
                            "age" : "25",
                            "source" : [
                                    {
                                            "source" : "srcOne"
                                    }
                            ]
                    },
                    {
                            "name" : "ABC",
                            "age" : "19",
                            "source" : [
                                    {
                                            "source" : "srcTwo"
                                    }
                            ]
                    }
            ]
    }

When am trying to query for name with XYZ and age with 19 its matching and giving the result which should not because name is matched with different object and age with different, how can i do a and query for the same object so that i matched exactly with complete Object. Below is the java code it gives me the result but i expect it shouln't

Document findDocument2=new Document();
Document findDocument3=new Document();
ArrayList<Document> a=new ArrayList<>();


findDocument2.append("name.name", "XYZ");
findDocument3.append("name.age", "19");
a.add(findDocument2);
a.add(findDocument3);

Document resDoc = mongoDatabase.getCollection("entity").find(Filters.and(findDocument2,findDocument3)).first();
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>> "+resDoc);
Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
Shaik Mujahid Ali
  • 2,308
  • 7
  • 26
  • 40
  • If all the values match in the same object only then i should get the matched document else not. The above link is grouping which is not i am looking for. – Shaik Mujahid Ali Sep 04 '15 at 15:05
  • Read the `$elemMatch` documentation as linked as well as the answers that use it. It **Is** what you are looking for. The `$elemMatch` operator compares "each" array element just like normal query arguments do to makes sure that "all" conditions are met for that particular element, and not for the whole array. And just because you complain ( again ) that you don't think your question is a duplicate ( again ) does not mean we have to listen. Very easy and simple research. – Blakes Seven Sep 04 '15 at 15:08

0 Answers0