需要一些关于基于子文档属性值的mongo查询的帮助,同时还要禁止该子文档属性出现在结果中。
以下是我的用户对象:

{
  "username" : "abc",
  "emails" : [
    {
      "address" : "abc1@email.com",
      "default" : true
    },
    {
      "address" : "abc2@email.com",
      "default" : false
    }
  ]
},
{
  "username" : "xyz",
  "emails" : [
    {
      "address" : "xyz1@email.com",
      "default" : false
    },
    {
      "address" : "xyz2@email.com",
      "default" : true
    }
  ]
}

我的目标是获得以下输出(使用“emails.default”:true,但结果中不显示“emails.default”属性):
{
  "username" : "abc",
  "emails" : [
    {
      "address" : "abc1@email.com",
    }
  ]
},
{
  "username" : "xyz",
  "emails" : [
    {
      "address" : "xyz2@email.com",
    }
  ]
}

使用$positional运算符:
collection.find({"emails.default":true}, {"username":1,"emails.$":1})

我得到了要显示的正确电子邮件子文档,但仍然得到了“emails.default”属性:
{
  "username" : "abc",
  "emails" : [
    {
      "address" : "abc1@email.com",
      "default" : true
    }
  ]
},
{
  "username" : "xyz",
  "emails" : [
    {
      "address" : "xyz2@email.com",
      "default" : true
    }
  ]
}

出于某种原因,当我使用这个语句时:
collection.find({"emails.default":true}, {"username":1,"emails.address":1})

我得到了以下结果(好像忽略了语句的查询部分)
{
  "username" : "abc",
  "emails" : [
    {
      "address" : "abc1@email.com",
    },
    {
      "address" : "abc2@email.com",
    }
  ]
},
{
  "username" : "xyz",
  "emails" : [
    {
      "address" : "xyz1@email.com",
    },
    {
      "address" : "xyz2@email.com",
    }
  ]
}

多谢帮忙,提前谢谢。

最佳答案

使用位置运算符(如MongoDB 2.6所示),您不能有选择地排除正在匹配的数组元素的字段。
但是,您可以使用MongoDB 2.2+中的聚合框架来实现您想要的结果:

db.user.aggregate(

    // Match on relevant documents to optimize query
    { $match: {
        username: "abc"
    }},

    // Convert the "emails" address into a stream of documents
    { $unwind: "$emails" },

    // Only include the emails with default:true
    { $match: {
        "emails.default" : true
    }},

    // Project the desired fields
    { $project: {
        _id : 0,
        username: 1,
        "emails.address": 1
    }}
)

样本结果:
{
    "username" : "abc",
    "emails" : {
        "address" : "abc1@email.com"
    }
}

09-30 13:04