2016-06-08 82 views
1

由不同的价值的完整资料我已经客户文档结构如下所示:检索使用猫鼬

{ 
    "name" : "blah" 
    "phone": "blah" 
    "customerId" : 123 
}, 
{ 
    "name" : "blah" 
    "phone": "blah" 
    "customerId" : 123 
}, 
{ 
    "name" : "blah" 
    "phone": "blah" 
    "customerId" : 256 
} 

我想以检索那些名字具有“B”字母的全文件:

Customer.find({"name": { '$regex' : req.query.name}}) 

是否有窍门,但我只希望每个customerId都有一个,这意味着我写了3个对象,我想要2个回来,其中一个客户ID为256,另一个客户ID为123.

回答

2

您需要为此使用汇总框架:

Customer.aggregate(
    [ 
     { "$match": { "name": { '$regex' : req.query.name } } }, 
     { "$group": { 
      "_id": "$customerId", 
      "name": { "$last": "$$ROOT" } } } 
    ], callback(err, result) 
)