Mongodb - 查询对象数组,但只返回一个属性

时间:2015-02-04 20:22:35

标签: arrays node.js mongodb mongoose mongodb-query

我不认为这是重复的,但如果我错了,请纠正我。无论如何,我想只返回“apple”和与用户的对象电子邮件地址匹配的客户成员角色。我使用$ elemMatch,但它返回整个客户对象,我只想要“成员”属性,就是这样。

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "orange" : "yes",
    "customers" : [ 
        {
            "name" : "Jay Smith",
            "email" : "jaysmith@example.com",
            "member" : "silver", 
        },
        {
            "name" : "Sarah Carter",
            "email" : "sarahcarter@example.com",
            "member" : "gold",
        },
        {
            "name" : "Jack Whatever",
            "email" : "jackwhatever@example.com",
            "member" : "gold",
        },
    ]
 }

理想的结果将是:

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "member" : "gold"
}

甚至这就足够了:

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "orange" : "yes",
    "customers" : [
         {"member" : "gold"}
    ]
}

这是我目前所拥有的:

   ItemsModel.find({ _id: { $in: _.pluck(user.items, 'itemId') }, active: true},
       {apple: 1, customers: {$elemMatch: {email: user.email}} }, 
           function(error, items) {
               if (error) { return next(error); }

                req.payload = {};
                req.payload.items = items;
                next();
            });

任何帮助都会非常感激。这甚至可能吗?谢谢!

1 个答案:

答案 0 :(得分:3)

ItemsModel.aggregate([
  { $unwind: '$customers' },
  { $match: { _id: { $in: _.pluck(user.items, 'itemId'), 'customers.email': user.email } },
  { $project : { _id:1 , apple:1, member:'$customers.member' }}
], function(err, res){
  // rest of your code here
})

会给你

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "member" : "gold"
}