Getting only the first item for an array property in mongodb
aggregation-framework, mongodb, mongodb-query
Solution
How about:
db.vehicles.find({"vehicle_id":1}, {images:{$slice: 1}})
Source: http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
Example
db.vehicles.insert({"vehicle_id": 1, "mfg_year": "1928", "mfg_make": "Ford", "mfg_model": "Model A", "images": [{"url":"www.a.com"}, {"url":"www.b.com"}, {"url":"www.c.com"}]})
db.vehicles.insert({"vehicle_id": 2, "mfg_year": "1999", "mfg_make": "BMW", "mfg_model": "Model B", "images": [{"url":"www.a.com"}, {"url":"www.b.com"}, {"url":"www.c.com"}]})
db.vehicles.insert({"vehicle_id": 3, "mfg_year": "1998", "mfg_make": "FMerc", "mfg_model": "Model C", "images": [{"url":"www.a.com"}, {"url":"www.b.com"}, {"url":"www.c.com"}]})
//now the query
db.vehicles.find({"vehicle_id":1}, {images:{$slice: 1}})
Output:
{
"vehicle_id" : 1,
"mfg_year" : "1928",
"mfg_make" : "Ford",
"mfg_model" : "Model A",
"images" : [
{
"url" : "www.a.com"
}
]
}
EDIT
You can specify just the fields you want to return like this:
db.vehicles.find({"vehicle_id":1}, {"mfg_make":1, images:{$slice: 1}})
So, in this instance, only the `mfg_make` and `images` is returned.
Another....
db.vehicles.find({"vehicle_id":1}, {"mfg_make":1, "some_other_field":1, images:{$slice: 1}})
If this were a RDBMS, this query is equivalent to:
SELECT mfg_make, some_other_field FROM tblVehicles WHERE vehicle_id = 1
Problem
Given the following layout in a collection... ``` { vehicle_id: 1 ,// bunch of properties I don't want ,vehicle: { mfg_year: 1928 ,mfg_make: "Ford" ,mfg_model: "Model A" ,mfg_trim: "T-Bucket" ,// bunch of properties I don't want ,images: [ {url:'...',...} ,... ] } } ``` How would I return a result with only the above fields, and only the first result under images? I don't mind if the results are in one flattened object, with only the images being a nested object. I've looked into the Aggregation Framework, which doesn't seem to match what I am looking for. I know I could do a map/reduce on the results set, or do a group on the listing_id, am just hoping to have a simpler query structure without needing to resort to group, or reduce. If this isn't possible currently via the aggregation framework, a working group or map-reduce would be an acceptable answer. EDIT: There are about 50+ properties that I don't want in the final result.. with the $slice directive, it seems I can't just specify the fields I want.