2016-07-20 86 views
1

帮我请: 一个有这样的指令集与此架构:如何从文档中的当前字段获取数组值?

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} 
}, 

);

和一个像这样的10个文档,我必须做什么查询才能从每个文档中获取“orderTime”数组?谢谢

+1

您可以提供您想要创建结果的一个例子吗? ta – robjwilkins

+0

[{createdTime:“..... time”},{createdTime:“..... time”},{createdTime:“...... time”}] –

+0

或[createdTime,createdTime。 ..] –

回答

1

使用聚合框架来创建数组。基本上,您想要将所有文档分组,使用累加器运算符创建列表。按照这个例子中得到的要点:

Order.aggregate([ 
    { 
     "$group": { 
      "_id": 0, 
      "orderTimes": { "$push": "$orderTime" }   
     } 
    } 
]).exec(function(err, result) { 
    console.log(result[0].orderTimes); 
}); 
+1

谢谢,这就是我想要的! –

2

假设你有这看起来是这样的文件:

{ 
     "_id" : ObjectId("578f73d17612ac41eb736641"), 
     "createdAt" : ISODate("2016-07-20T12:51:29.558Z") 
} 
{ 
     "_id" : ObjectId("578f73e57612ac41eb736642"), 
     "createdAt" : ISODate("2016-07-20T12:51:49.701Z") 
} 

那么你就可以生成包含createdAt日期,看起来像这样的数组结果文件:

{ "_id" : null, "creationDates" : [ ISODate("2016-07-20T12:51:29.558Z"), ISODate("2016-07-20T12:51:49.701Z") ] } 

运行下面的汇总查询:

db.<your_collection>.aggregate([{$group:{"_id":null,"creationDates":{$push:"$createdAt"}}}]) 

这将基本上组集合("_id":null)中的所有文档,并推动从createdAt字段中的值到一个数组("creationDates":{$push:"$createdAt"}

相关问题