2017-02-21 55 views
1

我有对象,如:db.collection.group显示其他属性也

{ 
foo: "A", 
bar: "Alpha" 
}, 
{ 
foo: "A", 
bar: "Alphabet" 
}, 
{ 
foo: "B", 
bar: "Beta" 
} 

我使用这个查询。它返回诸如对象:

{ 
    foo: "A" 
}, 
{ 
    foo: "B" 
} 

但我希望他们能够显示如:

{ 
foo: "A", 
bar: "Alpha" 
}, 
{ 
foo: "B", 
bar: "Beta" 
} 

它并不真正的问题,其价值将在bar被显示,但我需要的任何值。如果我还包含bar,key参数到group属性对象,我会得到很多重复项,但我只需要0123.字段的唯一身份码,而bar可以来自与foo组匹配的任何对象的值。

+1

使用gro聚合。 db.colection.aggregate([{$ group:{_id:“$ foo”,bar:{$ first:“$ bar”}}}]) – Veeram

+1

正确使用聚合函数 –

回答

2

使用db.collection.aggregate()$group阶段为:

db.collectionName.aggregate([ 
    { 
     "$group": { 
      "_id": "$foo", 
      "bar": { "$first": "$bar" } 
     } 
    } 
]) 

为了得到确切的输出,推另一个$project流水线阶段到最终输出格式为:

db.collectionName.aggregate([ 
    { 
     "$group": { 
      "_id": "$foo", 
      "bar": { "$first": "$bar" } 
     } 
    }, 
    { 
     "$project": { 
      "_id": 0, 
      "foo": "$_id", 
      "bar": 1 
     } 
    } 
]) 
+1

顺便提一下,'$ fist'正确?你是不是指'先'? – Kunok

+0

感谢您注意到错字:) – chridam