【问题标题】:excluding from $match if data is blank or null in mongodb如果数据在 mongodb 中为空白或 null,则从 $match 中排除
【发布时间】:2015-11-02 00:45:35
【问题描述】:

我在$match mongodb 遇到麻烦。

假设我有多个$match 选项,在某些情况下某些选项是blanknull 在那个阶段我想$match 匹配我们文档中的那个字段。

举例

$match:{
   name:'abc',
   age:''  //exclude if blank or null,
   city:'delhi'
}

我希望它只匹配 namecity 字段。如果 blanknull 可能从聚合中排除,我希望它排除 auto。

【问题讨论】:

标签: mongodb mongoose mongodb-query


【解决方案1】:

作为您的问题标题如果数据为空白或在 mongodb 中为空,则从 $match 中排除建议您要排除数据是否为空白和空。您应该使用$and 来匹配如下条件:

db.collection.aggregate({$match:{"name":"abc","city":"delhi","$and":[{"age":{"$ne":""}},{"age":{"$ne":null}}]}} )

【讨论】:

    【解决方案2】:

    我想你的文件是这样的:

    { "_id" : ObjectId("55c87313fc92af6b6b2f9497"), "name" : "abc", "age" : "", "city" : "delhi" }
    { "_id" : ObjectId("55c87314fc92af6b6b2f9498"), "name" : "abc", "age" : "", "city" : "delhi" }
    { "_id" : ObjectId("55c87314fc92af6b6b2f9499"), "name" : "abc", "age" : "", "city" : "delhi" }
    { "_id" : ObjectId("55c87319fc92af6b6b2f949a"), "name" : "abc", "age" : 2, "city" : "delhi" }
    { "_id" : ObjectId("55c8731cfc92af6b6b2f949b"), "name" : "abc", "age" : 3, "city" : "delhi" }
    { "_id" : ObjectId("55c87320fc92af6b6b2f949c"), "name" : "abc", "age" : 4, "city" : "delhi" }
    { "_id" : ObjectId("55c87324fc92af6b6b2f949d"), "name" : "abc", "city" : "delhi" }
    { "_id" : ObjectId("55c87325fc92af6b6b2f949e"), "name" : "abc", "city" : "delhi" }
    { "_id" : ObjectId("55c87326fc92af6b6b2f949f"), "name" : "abc", "city" : "delhi" }
    

    这里我想age 类型是Double

    您需要使用$exists$type 运算符。第一个过滤存在age 的文档,后者过滤其值不为空的文档。

    db.collection.aggregate([
        { "$match": { "name": "abc", "age": { "$exists": true, "$type": 1 }}}
    ])
    

    上面的写法更简洁:

    db.collection.aggregate([
        { "$match": { "name": "abc", "age": { "$type": 1 }, "city": "delhi" }}
    ])
    

    因为$type 运算符仅在字段存在 并且属于specified type 时才匹配。


    如果$match 是您的聚合 中唯一的管道运算符,那么您不需要聚合。只需使用.find 方法即可。

    db.collection.find({'name': 'abc', age: {$type: 1}, city: 'delhi' })
    

    输出:

    { "_id" : ObjectId("55c87319fc92af6b6b2f949a"), "name" : "abc", "age" : 2, "city" : "delhi" }
    { "_id" : ObjectId("55c8731cfc92af6b6b2f949b"), "name" : "abc", "age" : 3, "city" : "delhi" }
    { "_id" : ObjectId("55c87320fc92af6b6b2f949c"), "name" : "abc", "age" : 4, "city" : "delhi" }
    

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2017-10-22
      相关资源
      最近更新 更多