2017-08-14 35 views
1

我是MongoDB的新手,我想过滤一个内部数组。当前文档的样子:MongoDB找到内部数组

{ 
    "data1": "value1", 
    "data2": "value2", 
    ... 
    "array1": [ 
     { 
      "field1": field1value" 
      "field2": field2value" 
     }, 
     { 
      "field1": expectedvalue" 
      "field2": field2value" 
     }, 
    ] 
} 

我期待像一个结果:

{ 
    "data1": "value1", 
    "data2": "value2", 
    ... 
    "array1": [ 
     { 
      "field1": expectedvalue" 
      "field2": field2value" 
     }, 
    ] 
} 

我试图找到并聚集在In MongoDB, how do I search in an array of sub-documents?和其他类似的问题建议。

的问题是,我失去所有的信息的阵列(数据1,数据2,...)以外:

{ 
    "_id" : { "$oid" : "8001212651b8a68278edbc92"}, 
    "array1": [ 
     { 
      "field1": expectedvalue" 
      "field2": field2value" 
     }, 
    ] 
} 

回答

1

要仅在array1阵列相匹配,你必须给定的条件,其在返回的子文档projectfilter(可用于版本> = 3.2)。这里有一个例子:

db.collection.aggregate([ 
    // this is optional, it is only included here to show you that you _can_ match 
    // the documents before you match the array of sub documents 
    {$match: {data1: 'value1'}}, 
    {$project: { 
      data1: 1, 
      data2: 1, 
      array1: {$filter: { 
       input: '$array1', 
       as: 'a', 
       cond: {$eq: ['$$a.field1', 'expectedvalue']} 
      }} 
     }} 
]) 

这将返回如下:

{ 
    "_id" : ..., 
    "data1" : "value1", 
    "data2" : "value2", 
    "array1" : [ 
     { 
      "field1" : "expectedvalue", 
      "field2" : "field2value" 
     } 
    ] 
} 

您链接到答案这样的情况下,你需要通过Java驱动程序来运行此查询涉及蒙戈Java驱动程序,在这里它是:

List<Document> documents = collection.aggregate(Arrays.asList(
      new Document("$project", new Document() 
        // include data1 
        .append("data1", 1) 
        // include data2 
        .append("data2", 1) 
        // include only those elements of array1 which match the filter condition 
        .append("array1", new Document("$filter", 
          new Document("input", "$array1") 
            .append("as", "a") 
            .append("cond", new Document("$eq", Arrays.asList("$$a.field1", "expectedvalue")))))) 
    )).into(new ArrayList<>()); 
+0

只是一个问题:我可以在结果中获取data1,data2,...的值,而不是在生成的文档中明确地获取/设置它的值吗? – user1383093

+0

为了过滤子文档数组,您必须使用'$ project'运算符,并且由于您正在使用'$ project'运算符,所以您必须告诉MongoDB您要投影的内容,即您必须明确包含'data1', 'data2'等,通过向'$ project'文件中添加条目,如:'attribute_name:1'。 – glytching

+0

好的,非常感谢。我想我可以做一些事情,比如'用我新过滤的数组替换我的旧数组',而不需要再次创建所有原始*文档*数组外部的数据,因为它保持不变。 – user1383093