Before $unwind check if sub document is not empty

ⅰ亾dé卋堺 提交于 2019-12-31 03:49:26

问题


I have a Job schema that has job_title, job_location, salary, etc

ApplicationSchema is embedded sub document into Job document and it stores all the applications that this particular job has received

Here is how Job Schema looks

const jobSchema = new Schema({
  job_title : {
    type : String,
    required : true
  },
  job_location : {
    type : String,
  },
  salary : {
    type : Number
  },
  applications: [ApplicationSchema],
  companyId : {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Company'
  }
},{timestamps : true});

var Job = mongoose.model('Job', jobSchema);

module.exports = Job;

And you can see above applications sub document.

here is how my job document looks when there is no application for a particular job

 {
"_id" : ObjectId("5ac873c3bb7a9c3168ff159e"),
    "applications" : [],
    "job_title" : "Junior Developer",
    "companyId" : ObjectId("5ac870d0bb7a9c3168ff159c"),
    "createdAt" : ISODate("2018-04-07T07:31:15.257Z"),
    "updatedAt" : ISODate("2018-04-07T09:20:52.237Z"),
    "__v" : 2,
    "job_location" : "Pune, Maharashtra, India",
    "salary" : 3
}

And with applications

   {
    "_id" : ObjectId("5ac873c3bb7a9c3168ff159e"),
        "applications" : [ 
            {
                "applied" : true,
                "shortlisted" : false,
                "interviewed" : false,
                "offered" : false,
                "hired" : false,
                "rejected" : false,
                "rejectedComment" : ""
            }, 
            {
                "applied" : true,
                "shortlisted" : false,
                "interviewed" : false,
                "offered" : false,
                "hired" : false,
                "rejected" : false,
                "rejectedComment" : ""
            }
        ],
        "job_title" : "Junior Developer",
        "companyId" : ObjectId("5ac870d0bb7a9c3168ff159c"),
        "createdAt" : ISODate("2018-04-07T07:31:15.257Z"),
        "updatedAt" : ISODate("2018-04-07T09:20:52.237Z"),
        "__v" : 2,
        "job_location" : "Pune, Maharashtra, India",
        "salary" : 3
    }

And here is query

var jobsQuery = [
      {
        $match: {
          companyId: mongoose.Types.ObjectId(req.body.companyId),
          active: req.body.active
        }
      },
      {
        $unwind: "$applications"
      },
      {
        $match : query
      },
      {
        "$group":
                {
                  "_id": "$job_title",
                  "job_title": {$first: "$_id"},
                  "job_location": {$first: "$job_location"},
                  "min_experience": {$first: "$min_experience"},
                  "max_experience": {$first: "$max_experience"},
                  "min_salary": {$first: "$min_salary"},
                  "max_salary": {$first: "$max_salary"},
                  "createdAt": {$first: "$createdAt"},
                  "userId": {$first: "$userId"},

                  "applied": {"$sum":
                                   {"$cond":
                                           [{"$and": [
                                             {"$eq":["$applications.applied", true]},
                                             {"$eq":["$applications.shortlisted", false]},
                                             {"$eq":["$applications.interviewed", false]},
                                             {"$eq":["$applications.offered", false]},
                                             {"$eq":["$applications.hired", false]},
                                             {"$eq":["$applications.rejected", false]},
                                           ]},
                                           1,0]
                                   }
                             },

                }
      },
      {
          "$lookup":
              {
                  from: "users",
                  localField: "userId",
                  foreignField: "_id",
                  as: "userDetail"
              }
      },
    ]

When a job has received applications it works perfectly fine but when it has not, It can't $unwind and that's where i am getting nothing

So how can i give some condition so this query works with and without any applications

i am also querying for counting applicants in applied stage and i have other stages too.


回答1:


You need to add preserveNullAndEmptyArrays property inside your $unwind operation like this:

{
 $unwind:
  {
    path: "$applications",
    preserveNullAndEmptyArrays: true
  }
}

If true, if the path is null, missing, or an empty array, $unwind outputs the document. If false, $unwind does not output a document if the path is null, missing, or an empty array.

$unwind




回答2:


You need $exists and $ne operator in your $match stage.

Your $match stage will looklike

{
 $match: {
  companyId: mongoose.Types.ObjectId(req.body.companyId),
  active: req.body.active,
  applications:{$exists:true,$ne:[]}
 }
}

Your complete pipeline will look like

 [
      {
        $match: {
          companyId: mongoose.Types.ObjectId(req.body.companyId),
          active: req.body.active,
          applications:{$exists:true,$ne:[]}
        }
      },
      {
        $unwind: "$applications"
      },
      {
        $match : query
      },
      {
        "$group":
                {
                  "_id": "$job_title",
                  "job_title": {$first: "$_id"},
                  "job_location": {$first: "$job_location"},
                  "min_experience": {$first: "$min_experience"},
                  "max_experience": {$first: "$max_experience"},
                  "min_salary": {$first: "$min_salary"},
                  "max_salary": {$first: "$max_salary"},
                  "createdAt": {$first: "$createdAt"},
                  "userId": {$first: "$userId"},

                  "applied": {"$sum":
                                   {"$cond":
                                           [{"$and": [
                                             {"$eq":["$applications.applied", true]},
                                             {"$eq":["$applications.shortlisted", false]},
                                             {"$eq":["$applications.interviewed", false]},
                                             {"$eq":["$applications.offered", false]},
                                             {"$eq":["$applications.hired", false]},
                                             {"$eq":["$applications.rejected", false]},
                                           ]},
                                           1,0]
                                   }
                             },

                }
      },
      {
          "$lookup":
              {
                  from: "users",
                  localField: "userId",
                  foreignField: "_id",
                  as: "userDetail"
              }
      },
    ] 

For more https://docs.mongodb.com/manual/reference/operator/query/exists/



来源:https://stackoverflow.com/questions/49706751/before-unwind-check-if-sub-document-is-not-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!