2013-07-12 36 views
0

如果我有文件類似下面的集合:蒙戈選擇文檔中的所有獨特的組合屬性

{a:'1', b:'2', c:'3', d:'a'}, 
{a:'1', b:'2', c:'1', d:'b'}, 
{a:'1', b:'2', c:'3', d:'c'}, 
{a:'1', b:'3', c:'1', d:'d'}, 
{a:'1', b:'2', c:'3', d:'e'}, 
{a:'2', b:'2', c:'1', d:'f'} 

什麼是最有效的蒙戈查詢來獲得屬性A,B的所有唯一組合, C?可能嗎?結果看起來像:

{a:'1', b:'2', c:'3', d:*}, 
{a:'1', b:'2', c:'1', d:*}, 
{a:'1', b:'3', c:'1', d:*}, 
{a:'2', b:'2', c:'1', d:*} 

* =不在乎

謝謝,您的幫助表示讚賞。

回答

0

你可以嘗試這樣的事情

db.<your collection>.aggregate([{$group:{"a": "$a", "b": "$b", "c": "$c"}}]) 

也嘗試此鏈接mongodb get distinct records

我不是專業的MongoDB,但我認爲你也可以用js函數,就像這樣:

a = {} 
db.<your collection>.find().forEach(
    function(x) 
    { 
     if (a[[x.a, x.b, x.c]] == null) { 
      a[[x.a, x.b, x.c]] = true; 
      printjson(x); 
     } 
    } 
) 
0

這種操作的常用工具是distinct函數。不幸的是,MongoDB的distinct只能過濾一個字段(例如db.collection.distinct("a"))。各種解決方法都是可能的,例如使用aggregategroup

例與aggregate

db.collection.aggregate({ 
    $group: { 
     _id: { 
      a: "$a", 
      b: "$b", 
      c: "$c" 
     } 
    } 
}) 

你將不得不提取結果的信息,但我想這不是一個大問題。

group實施例:

db.collection.group({ 
    key: { 
     a: 1, 
     b: 1, 
     c: 1 
    }, 
    reduce: function (current, result) {}, 
    initial: {} 
})