【问题标题】:Advanced query with mongodb with several conditions具有多个条件的 mongodb 高级查询
【发布时间】:2022-01-27 00:21:16
【问题描述】:

我的 mongodb 文档包含对象 CarData,其中包含多个属性。

{
   _id: ...,
   Name: "",
   CarData: {
     carId: null,
     ownerName: "",
     ownerPhone: "",
     AdditionalInfo:{
       RefNr: ""
       validDoc: true
    }
   }
}

我知道我可以查询整个集合

{ "CarData": { $exists: true } }

但我不知道如何查询整个集合

CarData exists and is not null 
and ownerName != "" 
and AdditionalInfo exists and  != null 
and AdditionalInfo.validDoc == true

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    在 mongo 中,您无需在检查内部属性之前检查字段是否存在。我认为这对你来说应该足够了。 Playground

    db.collection.find({
      "CarData.ownerName": {
        "$ne": ""
      },
      "CarData.AdditionalInfo.validDoc": true
    })
    

    【讨论】:

      【解决方案2】:

      根据您的规范获取文件。你必须使用 MongoDB 提供的aggregation。下面的查询将满足您的要求。

      db.collection.aggregate([
        {
          $match: {
            "$and": [
              {
                CarData: {
                  "$exists": true
                }
              },
              {
                CarData: {
                  "$ne": null
                }
              },
              {
                "CarData.ownerName": {
                  $ne: ""
                }
              },
              {
                $and: [
                  {
                    "CarData.AdditionalInfo": {
                      "$exists": true
                    }
                  },
                  {
                    "CarData.AdditionalInfo": {
                      "$ne": null
                    }
                  },
                  {
                    "CarData.AdditionalInfo.validDoc": true
                  }
                ]
              }
            ]
          }
        }
      ])
      

      上面的查询会给出符合条件的文档列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多