猫鼬只从数组中获取特定对象,如果没有则从空数组中获取

时间:2020-05-04 23:57:13

标签: mongodb mongoose mongodb-query aggregation-framework

所以我有一个问卷调查模型:

const schema = new mongoose.Schema({
  title: String,
  category: String,
  description: String,
  requirementOption: String,
  creationDate: String,
  questions: [],
  answers: []
})

如您所见,答案是一个数组。该数组包含具有此结构的对象

{
  "participantEmail": "someEmail@email.email"      
  "currentIndex": 14,
  ...
}

现在,我想按ID获取特定的调查问卷,但是在答案数组中,我只需要特定的参与者电子邮件。因此,答案数组应具有一个元素或没有元素。但是,如果答案数组中没有这样的电子邮件,我不想得到null的结果。

我想出了如何通过此查询从数组中获取特定元素:

dbModel.findOne({_id: id, 'answers': {$elemMatch: {participantEmail: "someEmail@email.com"}}}, {'answers.$': 1}).exec();

如果该电子邮件存在于答案数组中,我将得到此消息:

 "data": {
    "questionnaireForParticipant": {
      "id": "5d9ca298cba039001b916c55",
      "title": null,
      "category": null,
      "creationDate": null,
      "description": null,
      "questions": null,
      "answers": [
        {
          "participantEmail": "someEmail@email.com",
          ....
         }

    }
  }

但是,如果该电子邮件不在答案数组中,我将只得到null。另外,我想获得titlecategory以及所有其他字段。但是我似乎找不到办法。

2 个答案:

答案 0 :(得分:1)

由于您在'answers': {$elemMatch: {participantEmail: "someEmail@email.com"}}的过滤器部分中遇到了.findOne()这个条件-如果对于给定的_id文档,在answers. participantEmail数组中没有元素与输入值{{ 1}},然后"someEmail@email.com"将返回.findOne()作为输出。因此,如果您想返回文档而与null数组中是否存在匹配元素无关,请尝试以下查询:

answers

测试: mongoplayground

参考: aggregation-pipeline

注意::由于您想返回具有匹配元素的db.collection.aggregate([ { $match: { "_id": ObjectId("5a934e000102030405000000") } }, /** addFields will re-create an existing field or will create new field if there is no field with same name */ { $addFields: { answers: { $filter: { // filter will result in either [] or array with matching elements input: "$answers", cond: { $eq: [ "$$this.participantEmail", "someEmail@email.com" ] } } } } } ]) 数组或空数组,因此我们使用了聚合。另外,您可以根据需要使用answers而不是$project来转换输出。

答案 1 :(得分:1)

接受的答案是正确的,但是如果您像我一样使用猫鼬,这就是您必须编写接受的答案查询的方式:

>>> DT_EX[:, count(), by(f.cust_life_cycle, f.cid)]\
...      [:, {"unique_cids": count()}, by(f.cust_life_cycle)]

   | cust_life_cycle  unique_cids
-- + ---------------  -----------
 0 | Active                     2
 1 | Inactive                   2
 2 | Lead                       3

[3 rows x 2 columns]