Reputation:
I am testing the grouping feature in mongodb.
The group function takes an object as an argument. Within the object they have a key called cond
of which value can be used as query to match documents.
I am passing a valid query that matches more than one document. But grouping returns only the last matched document's result. I think i am missing something here to make group
function return all the matched documents results.
The steps i have done are,
db.test.insert({user:{name:"xxxx1"}});
db.test.insert({user:{name:"xxxx2"}});
db.test.insert({user:{name:"xxxx3"}});
db.test.insert({user:{name:"xxxx4"}});
db.test.insert({user:{name:"xxxx5"}});
db.test.insert({user:{name:"xxxx6"}});
db.test.group({
initial:{name:'', id:''},
reduce:function(d, o){o.name = d.user.name; o.id=d._id;},
finalize:function(o){},
cond:{"user.name":/^x/}
});
The above command returns
[
{
"name" : "xxxx6", "id" : ObjectId("4edf72baec65faac52976e72")
}
]
Its the last inserted document.
What should i to get all the matched results!?
Thanks
Upvotes: 0
Views: 304
Reputation: 30136
"return all the matched documents results" means you probably want to do a query instead of a group. Grouping would be used to aggregate documents based on a key instead of simply returning all of the ones that match (what you want).
Just do db.collection.find(query-document)
, which in your case would be:
db.test.find({"user.name": /^x/})
Update to address new information:
"i dont want to send complete document"
Then use the second parameter of find in order to provide a document that has the fields you want { "user.name": 1 }
. Keep in mind that _id is included by default but you can exclude it if you want using {_id: 0}
.
As for the formatting, if storing the ordering is important then use an array. If order doesn't matter and it is for display purpose only do the ordering on the client side. Using map reduce to format the output is not the intended use and will only serve to slow the query down.
Upvotes: 1