2017-08-14 109 views
2

可以說我有看起來像這樣的一個蒙戈數據庫:如何編寫查詢對象內數組的mongo查詢?

[ 
    { 
    dec: 5972, 
    bin: [0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0] 
    }, 
    { 
    dec: 397250, 
    bin: [1,1,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,0] 
    }, 
    { 
    dec: 5, 
    bin: [0,1,0,1] 
    }, 
    { 
    dec: 123, 
    bin: [0,1,1,1,1,0,1,1] 
    } 
] 

如何查詢數據庫給我的所有對象的「0」和「1」在他們bin屬性的個數等於。 例如,我希望得到的結果只有:

{ 
    dec: 5, 
    bin: [0,1,0,1] 
}  

回答

1

在這裏你去:

db.test.aggregate([ 
{ 
    $project: { 
     dec: "$dec", 
     bin: "$bin", 
     original_bin: "$bin" 
    } 
}, 

{ 
    $unwind: "$bin" 
}, 
{ 
    $group: { 
     _id: { 
      dec: "$dec", 
      bin: "$bin", 
      original_bin: "$original_bin" 
     }, 

     total: { 
      $sum: 1 
     } 
    } 
}, 
{ 
    $group: { 
     _id: {dec: "$_id.dec", original_bin: "$_id.original_bin"}, 
     sums: { 
      $addToSet: "$total" 
     } 
    } 
}, 
{ 
    $match: { 
     sums: { 
      $size: 1 
     } 
    } 
}, 
{ 
    $project: { 
     _id: 0, 
     dec: "$_id.dec", 
     bin: "$_id.original_bin" 
    } 
} 
]); 

我有一個簡單的數據是這樣的:

{"dec":1,bin: [0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0]} 
{"dec":2,bin: [0,1,0,1,0,0]} 
{"dec":3,bin: [1,0,1,0,1,0]} 
{"dec":4,bin: [0,1,0,0]} 
{"dec":5,bin: [0,0,0,1,1,1]} 
{"dec":6,bin: [0,1]} 

在給定的查詢樣本數據返回所需陣列:

{ "dec" : 6, "bin" : [ 0, 1 ] } 
{ "dec" : 3, "bin" : [ 1, 0, 1, 0, 1, 0 ] } 
{ "dec" : 5, "bin" : [ 0, 0, 0, 1, 1, 1 ] }