有没有办法只返回mongodb文档中的数组中的某些元素

时间:2013-05-17 18:27:02

标签: mongodb mongodb-.net-driver

使用以下mongodb查询:

db.StyleHeader.find({ "FlexContent.ExtendedContent" : { "$elemMatch" : { "Defines" : "Old Keywords" } } }, { "FlexContent.ExtendedContent.Defines" : true, "FlexContent.ExtendedContent.Value" : true }).limit(50);

我得到以下结果:

{
  "_id" : 1331142,
  "FlexContent" : {
    "ExtendedContent" : [{
        "Defines" : "Content Keywords",
        "Value" : "FST-SET, SIZING_CHART-WOMENS_SIZING"
      }, {
        "Defines" : "Search Keywords",
        "Value" : "Closeout, Sale, Tops, T-Shirt, Womens"
      }, {
        "Defines" : "Exceptions",
        "Value" : ""
      }, {
        "Defines" : "Old Keywords",
        "Value" : "1020A20,PRT,SML,Let's,Tour,W.,S9S,T,Shirt,By,Twin,Six,#1C,PRINT,SM,1020A20PRTSML,WEBSORTZ,CAT-TOPS-WOMENS-ALL,1020898ZZ,1010A17ZZ,1020A21ZZ,1020902ZZ,1020904ZZ,CAT-TWINSIX,CAT-GIFTIDEAS,CAT-GIFTS-30,CAT-GIFTS-50,1020903ZZ,CAT-GIFTS-NEW,CAT-TOPS-WOMENS-TSHRT,CAT-GIFTS-HER,CAT-TOPS-TSHIRT,SIZING_CHART-WOMENS_SIZING,CAT-GIFTS-ALL,FST.-SET,FGT.-TSHIRT,CAT-SALE-ALL,CAT-SALE-TOPS,ZKQX,CO_01,DIV_00,CAT1_BA,CAT2_AC"
      }, {
        "Defines" : "Name",
        "Value" : "Let's Tour Women's Short Sleeve T Shirt By Twin Six  "
      }, {
        "Defines" : "Base Item",
        "Value" : "1020A20 PRT SML"
      }, {
        "Defines" : "Price",
        "Value" : "21.95"
      }, {
        "Defines" : "Upsells",
        "Value" : "1010A17, 1020898, 1020902, 1020903, 1020904, 1020A21"
      }, {
        "Defines" : "Default Customization Template",
        "Value" : "not applicable"
      }, {
        "Defines" : "Product Description Style",
        "Value" : "None"
      }, {
        "Defines" : "Promo Search",
        "Value" : ""
      }, {
        "Defines" : "Auto Customization",
        "Value" : ""
      }]
  }
}

我真的只需要定义“搜索关键字”的ExtendedContent。

有没有办法修改我的查询,以便结果看起来更像这样:

{
  "_id" : 1331142,
  "FlexContent" : {
    "ExtendedContent" : [{
        "Defines" : "Search Keywords",
        "Value" : "Closeout, Sale, Tops, T-Shirt, Womens"
      }]
  }
}

我正在尝试首先在MongoVUE中找出查询结构,但最终这将使用C#驱动程序完成,因此任何一种解决方案都适用于我。

1 个答案:

答案 0 :(得分:2)

您可以使用$ positional projection operator执行此操作:

 
db.StyleHeader.find(
    { "FlexContent.ExtendedContent" : { 
        "$elemMatch" : { "Defines" : "Old Keywords" } 
    } },
    { "FlexContent.ExtendedContent.$" : true }
).limit(50);

甚至更简单(因为您只匹配ExtendedContent数组元素中的一个字段):

 
db.StyleHeader.find(
    { "FlexContent.ExtendedContent.Defines" : "Old Keywords" },
    { "FlexContent.ExtendedContent.$" : true }
).limit(50);