MongoDB获取嵌套在对象数组中的对象数组中的单个对象

时间:2018-01-02 11:09:09

标签: arrays mongodb mongoose aggregation-framework javascript-objects

如何基于一些属性值来访问嵌套在另一个对象数组中的对象数组中的单个对象,如伪代码中的这样:

SELECT DAY = 1 WHERE _id = 5a3469f22dc3784bdd9a6190 AND MONTH = 12

下面列出了Mongoose模型架构。根据需要,子文档的列出高于其相应的父项,dailySchedulesSchema是最高的:

var dailySchedulesSchema = new mongoose.Schema({
    day: Number,
    dayStart: Number,
    firstBreakStart: Number,
    firstBreakEnd: Number,
    lunchStart: Number,
    lunchEnd: Number,
    secondBreakStart: Number,
    secondBreakEnd: Number,
    dayEnd: Number,
    workDuration: Number
});

var monthlyScheduleSchema = new mongoose.Schema({
    month: {type: Number, required: true },
    dailySchedules: [dailySchedulesSchema]
});

var employeeSchema = new mongoose.Schema({
    name: {type: String, required: true},
    surname: {type: String, required: true},
    email: {type: String, required: true},
    phone: {type: String, required: true},
    occupation: {type: String, required: true},
    status: {type: Boolean, required: true},
    monthlySchedule: [monthlyScheduleSchema]
});

这是我正在尝试处理的数据库中的员工条目。:

"_id" : ObjectId("5a3469f22dc3784bdd9a6190"),
        "name" : "Eric",
        "surname" : "K. Farrell",
        "email" : "EricKFarrell@dayrep.com",
        "phone" : "864-506-7281",
        "occupation" : "Employee",
        "status" : true,
        "monthlySchedule" : [
                {
                        "month" : 12,
                        "dailySchedules" : [
                                {
                                        "day" : 1,
                                        "dayStart" : 480,
                                        "firstBreakStart" : 600,
                                        "firstBreakEnd" : 615,
                                        "lunchStart" : 720,
                                        "lunchEnd" : 750,
                                        "secondBreakStart" : 870,
                                        "secondBreakEnd" : 885,
                                        "dayEnd" : 1020,
                                        "workDuration" : 480
                                },
                                {
                                        "day" : 2,
                                        "dayStart" : 540,
                                        "firstBreakStart" : 630,
                                        "firstBreakEnd" : 645,
                                        "lunchStart" : 750,
                                        "lunchEnd" : 780,
                                        "secondBreakStart" : 870,
                                        "secondBreakEnd" : 885,
                                        "dayEnd" : 1050,
                                        "workDuration" : 480
                                }
                        ]
                }
        ]
}

获得单日的路线本身是:“/ employees /:employeeid /:month /:day”

虽然我设法访问了父文档(比如列出所有员工),但我无法列出特定的子文档条目(例如该员工的特定日程安排) - mongoose已经返回了当月的所有现有日程表或者什么都没有:

(...)

  var sendJsonResponse = function(res, status, content){
        res.status(status);
        res.json(content);
    }

(...)

module.exports.empDayReadOne = function(req, res){
    var monthParam = req.params.month;
    var employeeid = req.params.employeeid;
    var dayParam = req.params.day;

    Emp
        .aggregate([
        {$match: {$and: [{'monthlySchedule': {$elemMatch: {$exists: true} } }, {_id: employeeid }] } },
        {$unwind:'$monthlySchedule'}, 
        {$unwind:'$monthlySchedule.dailySchedules'}, 
        {$match:{ $and:[ {'monthlySchedule.dailySchedules.day': dayParam},{'monthlySchedule.month': monthParam} ] } }

        ])
        .exec(function(err, dailySchedule){
            if(dailySchedule){
                sendJsonResponse(res, 200, dailySchedule);
            } else if(err){
                sendJsonResponse(res, 400, err);
                return;
            } else {
                sendJsonResponse(res, 404, {"message": "This day has no schedules added."});
                return;
            }

        });

};

1 个答案:

答案 0 :(得分:1)

您可以尝试以下聚合查询。

以下查询首先$filters monthlySchedule返回数组,其中包含匹配的月数组元素,后跟第二个过滤器,以检索dailySchedules数组中的匹配日元素。

$arrayElemAt将包含单个元素的数组转换为文档。

db.collection_name.aggregate([
  {"$match":{"_id":ObjectId("5a3469f22dc3784bdd9a6190")}},
  {"$project":{
    "dailyschedule":{
      "$arrayElemAt":[
        {"$filter":{
          "input":{
            "$filter":{
              "input":"$monthlySchedule",
              "cond":{"$eq":["$$this.month",12]}
            }
          },
          "cond":{"$eq":["$$this.day",1]
          }
        }},
      0]
    }
  }}
])

更新了Mongoose代码:

Emp.aggregate([
  {"$match":{"_id":mongoose.Types.ObjectId(employeeid)}},
  {"$project":{
    "dailyschedule":{
      "$arrayElemAt":[
        {"$filter":{
          "input":{
            "$filter":{
              "input":"$monthlySchedule",
              "cond":{"$eq":["$$this.month",monthParam]}
            }
          },
          "cond":{"$eq":["$$this.day",dayParam]
          }
        }},
      0]
    }
  }}
])