2017-02-06 70 views
0

的列表項我怎樣才能在"mol"列表中找到每個項目的長度:如何計算列表中的

例如,如果我找"versionA" : "2.1.2"我想到加時賽得到以下結果:

{"project" : "A", "scene" : 13455312, mol:[3,2,1]}, 
{"project" : "B", "scene" : 13455344, mol:[3,3,3]} 

我的數據:

{ 
     "project" : "A", 
     "scene" : 13455312, 
     "versionA" : "2.1.2", 
     "versionB" : "2.1.9", 
     "mol" : [ {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}, {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }]}, {"data" : [ { "tran" : 'A' }]}] 
    }, 

    { 
     "project" : "B", 
     "scene" : 13455344, 
     "versionA" : "2.1.2", 
     "versionB" : "2.1.9", 
     "mol" : [ {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}, {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}, {"data" : [ { "tran" : 'A' }, { "tran" : 'B' }, { "tran" : 'C' }]}] 
    }, 
    { 
     "project" : "C", 
     "scene" : 135555, 
     "versionA" : "2.1.3", 
     "versionB" : "2.1.9", 
     "mol" : [ {"data" : [ { "tran" : 'A' }]}, {"data" : [ { "tran" : 'A' }]}, {"data" : [ { "tran" : 'A' }]}] 
    } 

回答

1

可以$matchversion場和$map它迭代的mol$size來計算數據字段的長度。

db.collection.aggregate(
    [{ 
     $match: { 
      "versionA": "2.1.2" 
     } 
    }, { 
     $project: { 
      _id: 0, 
      "project": 1, 
      "scene": 1, 
      "mol": { 
       $map: { 
        input: "$mol", 
        as: "mo", 
        in: { 
         $size: "$$mo.data" 
        } 
       } 
      } 
     } 
    }] 
) 
+0

謝謝你正是我想要的。 –