2017-08-14 55 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