如何查询类型为object的字段与值匹配的所有文档

时间:2020-02-13 14:15:34

标签: javascript mongodb aggregate

我对使用MongoDB并不陌生,我遇到了一个问题,即选择所有字符串值与类型为object的字段中的一个字段匹配的文档。

这是我的文档结构:

{
    "_id" : ObjectId("5e418404bfa0c42c913b0646"),
    "date" : ISODate("2020-02-10T16:25:40.046Z"),
    "employee" : ObjectId("5e3d3019056065194c0d5f08"),
    "newClient" : {
        "firstname" : "Max",
        "lastname" : "Mustermann",
        "gender" : "M"
    },
    "status" : "DONE",
    "reportedAt" : ISODate("2020-02-10T16:25:40.046Z")
}

我想选择newClient.firstnamenew RexExp("max", "i")匹配的所有文档。

因为我需要$lookup来定义其他匹配项,所以我必须使用aggregate,它看起来像这样(简化):

db.getCollection('assignments').aggregate([
          {
            $lookup: {
              from: "clients",
              localField: "client",
              foreignField: "_id",
              as: "client"
            }
          },
          { $unwind: "$client" },
          {
            $match: {
              status: "DONE",
              $or: [
                {
// --- This are some examples I did, but non of it is working ---
                    // "assignments": { "$elemMatch": { "newClient.lastname": { $regex: "Android", $options: "i" } } }
                    // "assignments.newClient": { $elemMatch: { lastname: { $regex: "Android", $options: "i" } } }
                    // "newClient.*": new RegExp("Android", "i")
                }
              ]
            }
          },
        ]);

我该怎么做?

1 个答案:

答案 0 :(得分:0)

以下是一些有效的正则表达式条件:

db.assignments.aggregate([
   { $match: { $expr: { $regexMatch: { input: "$newClient.firstname", regex: "max", options: "i" } } } }
])

db.collection.aggregate([
   { $match: { $expr: { $regexMatch: { input: "$newClient.firstname", regex: /max/i } } } }
])

db.assignments.aggregate([
   { $match: { "newClient.firstname": /max/i } }
])

db.assignments.aggregate([
   { $match: { "newClient.firstname": { $regex: /max/i } } }
])

db.assignments.aggregate([
   { $match: { "newClient.firstname": { $regex: "max", $options: "i" } } }
])