【问题标题】:MongoDB (Mongoose) how to returning all document fields using $elemMatchMongoDB (Mongoose) 如何使用 $elemMatch 返回所有文档字段
【发布时间】:2014-02-01 06:09:19
【问题描述】:

根据 MongoDB 文档 (http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/):

{
 _id: 1,
 school: "school A",
 zipcode: 63109,
 students: [
              { name: "john", school: 102, age: 10 },
              { name: "jess", school: 102, age: 11 },
              { name: "jeff", school: 108, age: 15 }
           ]
}
{
 _id: 2,
 school: "school B",
 zipcode: 63110,
 students: [
              { name: "ajax", school: 100, age: 7 },
              { name: "achilles", school: 100, age: 8 },
           ]
}

{
 _id: 3,
 school: "school C",
 zipcode: 63109,
 students: [
              { name: "ajax", school: 100, age: 7 },
              { name: "achilles", school: 100, age: 8 },
           ]
}

{
 _id: 4,
 school: "school D",
 zipcode: 63109,
 students: [
              { name: "barney", school: 102, age: 7 },
           ]
}

发射:

schools.find({ zipcode: 63109}, {students: { $elemMatch: { school: 102 } } },函数(错误,学校){ ...}

该操作返回以下文档:

{“_id”:1,“学生”:[{“姓名”:“约翰”,“学校”:102,“年龄”: 10 } ] } { "_id" : 3 } { "_id" : 4, "学生" : [ { "name" : “巴尼”,“学校”:102,“年龄”:7 } ] }

但我也需要提交学校的价值...

{ "_id" : 1, "school": "School A", "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] } {“_id”:3,“学校”:“学校 C”} {“_id”:4,“学校”:“学校 D”,“学生”:[{“名称”: “巴尼”,“学校”:102,“年龄”:7 } ] }

我找不到实现这一目标的方法...

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    http://docs.mongodb.org/manual/reference/method/db.collection.find/

    如果指定了投影参数,则匹配文档 仅包含投影字段和 _id 字段。你可以 可选地排除 _id 字段。

    但是...我使用以下命令强制返回字段:

    schools.find({ zipcode: 63109}, {school: 1, students: { $elemMatch: { school: 102 } } }, function (err, school) { ...}
    

    一切似乎都正常...

    【讨论】:

      【解决方案2】:

      根据 mongodb [documentation][1] $elemMatch 根据条件从数组中返回 first 匹配元素。所以你必须使用 $filter 而不是 $elemMatch 来获取所有匹配的元素。

      我已经写了一个解决方案。请看一下。 解决方案检查链接:https://mongoplayground.net/p/cu7Mf8XZHDI

      db.collection.find({},
      {
        students: {
          $filter: {
            input: "$students",
            as: "student",
            cond: {
              $or: [
                {
                  $eq: [
                    "$$student.age",
                    8
                  ]
                },
                {
                  $eq: [
                    "$$student.age",
                    15
                  ]
                }
              ]
            }
          }
        }
      })
      
      
      
      
        [1]: http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/
      

      【讨论】:

        猜你喜欢
        • 2021-02-17
        • 2021-10-19
        • 1970-01-01
        • 2018-12-10
        • 1970-01-01
        • 2023-02-14
        • 2020-11-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多