2016-01-08 55 views
1

我想获得一个匹配数,因为我有一种问题,所以我会将我的find().count()更改为aggregate()方法。

我的问题是,当我添加我的$匹配它不会返回任何计数,如果我删除该行它的工作正常。

db.getCollection('product').aggregate(
    [ 
     { $match: { 'Store.Title': { $regex: '/apc/', $options: 'gi' } } }, 
     { $group: { _id: null, count: { $sum: 1 } } } 
    ] 
) 

有人可以帮我解释我在这里做错了吗?

回答

1

您可以尝试使用RegExp对象首先创建正则表达式对象,然后在您的管道使用它:

var apc_match = new RegExp('apc', 'gi'); 

db.getCollection('product').aggregate(
    [ 
     { $match: { 'Store.Title': apc_match } }, 
     { $group: { _id: null, count: { $sum: 1 } } } 
    ] 
); 

OR

db.getCollection('product').aggregate(
    [ 
     { $match: { 'Store.Title': { $regex: 'apc', $options: 'gi' } } }, 
     { $group: { _id: null, count: { $sum: 1 } } } 
    ] 
); 

OR

db.getCollection('product').aggregate(
    [ 
     { $match: { 'Store.Title': /apc/gi } }, 
     { $group: { _id: null, count: { $sum: 1 } } } 
    ] 
); 
+1

谢谢很多:)其工作炉排。 – ParisNakitaKejser

+1

@ParisNakitaKejser不用担心,乐意帮忙:-) – chridam