1

i am working with mongodb java . My document looks like this

 _id:ObjectId("abcd1234rf54")
createdDate:"12/11/15"
type:1
nameIdentity:[{"nameOne":"aa","nameTwo":"bb"},
{"nameOne":"aa","nameTwo":"dd"},
{"nameOne":"ee","nameTwo":"ff"}]

where nameIdentity is an array of documents. I am trying to query on nameIdentity if there is an exact match of document for eg {"nameOne":"aa","nameTwo":"dd"} i should get only {"nameOne":"aa","nameTwo":"dd"} document as output but i am getting the complete document . My query is

Document fields=new Document("nameOne","aa").append("nameTwo","bb");
Document elemMatch = new Document("$elemMatch", fields);
                Document exactElemMatch = new Document();
                exactElemMatch.append(MongoConstants.NAME_IDENTITY, elemMatch);
        Document        resultDocument = mongoDatabase.getCollection(test).find(exactElemMatch).first(); . With this i am getting the whole document but what i want id just the matching criteria i.e., `{"nameOne":"aa","nameTwo":"dd"}`. Where am i going wrong ? And is it possible to get the index of matched document ?
Shaik Mujahid Ali
  • 2,308
  • 7
  • 26
  • 40
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) as you as missing the positional `$` operator part of the projection in that statement. There are various examples there using the positional operator. – Blakes Seven Oct 08 '15 at 08:35
  • @BlakesSeven - is it possible to get the index of the matched document? – Shaik Mujahid Ali Oct 08 '15 at 09:11
  • That is what the [positional `$` operator](http://docs.mongodb.org/manual/reference/operator/projection/positional/) is for. It's takes the matched position of the array element found by the query and passes it into the projection to just return that matched element. This is shown in the top voted answer and at least three other answers posted on the duplicate. You need to include a "projection/field selection" after the `.find()`. – Blakes Seven Oct 08 '15 at 09:18
  • i got your point , but i need to print the index value. $ takes index value and matches. I just want the index value to be printed – Shaik Mujahid Ali Oct 08 '15 at 09:42
  • 2
    Ahh. Now that is not what your question asks. It is not possible from MongoDB itself, save using mapReduce. But there should be no point, unless arrays are really "huge". You test the array element in client code instead to find the index at which it matches, and do that per document. – Blakes Seven Oct 08 '15 at 09:52

0 Answers0