MongoDB query to limit values based on condition

Tags: arrays mongodb
Question!

I have a collection like this:

{ "_id" : ObjectId("4d45bd25957a15b80702d4e4"), "codenum" : 10, "payment" : [
 {
  "pcode" : 100,
  "amount" : 10000
 },
 {
  "pcode" : 101,
  "amount" : 6000
 }
], "age" : 70 }

Notice that payment array is embedded in this collection. Now, I would like to retrieve only payment code matching 101 in the find response.

Giving a query like this:

db.test.find({"codenum":10, "payment.pcode": 101}, 
             {"codenum":1, "payment.pcode":1, "payment.amount":1})

will get my entire document including other payment pcodes as well, as in the above display.

However, I require a response something like this:

{ "_id" : ObjectId("4d45bd25957a15b80702d4e4"), "codenum" : 10, "payment" : [
 {
  "pcode" : 101,
  "amount" : 6000
 }
] }

Is this possible in mongodb?

In update(), there is a positional match that can be used like "payment.$.amount" to set the matching field based on the condition.

May be MongoDB can support the query like this:

db.test.find({"codenum":10, "payment.pcode": 101}, 
             {"payment.$.pcode": 1, "payment.$.amount":1})

which would then give only those entries that match the condition given.

Any thoughts?

By : rsmoorthy


Answers
To my knowledge, it is not possible to select only a single entry from an array in MongoDB. You can return only certain fields from the document (ie, your payment array), but you cannot return only a portion of the array based on the query. (You can use $slice to return a particular index-delimited element, but that doesn't get you what you need here).

You must query either all of the field, or none of it. This JIRA ticket describes the problem, and it is currently "planned but not scheduled".

For the time being, you'll need to just extract the relevant part of the document in your application code.



This will get you what you need even though it is still in development. http://www.mongodb.org/display/DOCS/Aggregation+Framework

By : pdxwebdev


This video can help you solving your question :)
By: admin