Reputation: 227
help me please : a have such order collection with this schema :
const OrderSchema = new Schema(
{
doctorId: { type : Schema.Types.ObjectId, ref: 'Users'},
patientId: { type : Schema.Types.ObjectId, ref: 'Users'},
orderTime: { type : String , default:''},
createdAt: { type : Date, default:Date.now },
approvedByDoctor:{ type :Boolean, default:false },
price:{type:Number,default:0}
},
);
and a have 10 documents like this, what query must i do to get array of "orderTime" from each document? thanks
Upvotes: 1
Views: 36
Reputation: 5652
Assuming you have documents which look like this:
{
"_id" : ObjectId("578f73d17612ac41eb736641"),
"createdAt" : ISODate("2016-07-20T12:51:29.558Z")
}
{
"_id" : ObjectId("578f73e57612ac41eb736642"),
"createdAt" : ISODate("2016-07-20T12:51:49.701Z")
}
then you can generate a result document containing an array of createdAt dates which looks like this:
{ "_id" : null, "creationDates" : [ ISODate("2016-07-20T12:51:29.558Z"), ISODate("2016-07-20T12:51:49.701Z") ] }
by running the following aggregate query:
db.<your_collection>.aggregate([{$group:{"_id":null,"creationDates":{$push:"$createdAt"}}}])
this will basically group all documents in the collection ("_id":null
) and push the the values from the createdAt fields into an array ("creationDates":{$push:"$createdAt"}
)
Upvotes: 2
Reputation: 103305
Use the aggregation framework to create the array. Essentially you'd want to group all the documents, use the $push
accumulator operator to create the list. Follow this example to get the gist:
Order.aggregate([
{
"$group": {
"_id": 0,
"orderTimes": { "$push": "$orderTime" }
}
}
]).exec(function(err, result) {
console.log(result[0].orderTimes);
});
Upvotes: 1