如果数据为空或在mongodb中为null,则从$ match中排除

时间:2015-08-10 07:28:46

标签: mongodb mongoose mongodb-query

我在$match的{​​{1}}中遇到了麻烦。

假设我有多个mongodb选项,在某些情况下,某些选项$matchblank,我希望null匹配我们文档中的该字段。

例如

$match

我希望它仅匹配$match:{ name:'abc', age:'' //exclude if blank or null, city:'delhi' } name字段。我希望它可以从聚合中排除自动cityblank

2 个答案:

答案 0 :(得分:1)

如果您的问题标题从$ match中排除,如果数据为空或在mongodb中为null ,则表示您要排除数据为空且为空。您应该使用$and来匹配以下条件:

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

答案 1 :(得分:0)

我想你的文件看起来像这样:

{ "_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" }