我在$match
的{{1}}中遇到了麻烦。
假设我有多个mongodb
选项,在某些情况下,某些选项$match
或blank
,我希望null
匹配我们文档中的该字段。
例如
$match
我希望它仅匹配$match:{
name:'abc',
age:'' //exclude if blank or null,
city:'delhi'
}
和name
字段。我希望它可以从聚合中排除自动city
或blank
。
答案 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" }