Mongodb:如何从多个字段中选择不同的值
您可以使用以下语法在 MongoDB 中的多个字段中选择不同的值:
db.collection.aggregate( [ { $group : { "_id": { field1: " $field1 ", field2: " $field2 " } } } ] )
以下示例展示了如何在具有以下文档的催收团队中使用此语法:
db.teams.insertOne({team: " Mavs ", position: " Guard ", points: 31 }) db.teams.insertOne({team: " Mavs ", position: " Guard ", points: 22 }) db.teams.insertOne({team: " Rockets ", position: " Center ", points: 19 }) db.teams.insertOne({team: " Rockets ", position: " Forward ", points: 26 }) db.teams.insertOne({team: " Rockets ", position: " Forward ", points: 29 }) db.teams.insertOne({team: " Cavs ", position: " Guard ", points: 33 })
示例:在多个字段中选择不同的值
我们可以使用以下查询来查找所有不同的团队和位置字段值:
db.teams.aggregate( [ { $group : { "_id": { team: " $team ", position: " $position " } } } ] )
该查询返回以下文档:
{ _id: { team: 'Mavs', position: 'Guard' } } { _id: { team: 'Rockets', position: 'Forward' } } { _id: { team: 'Rockets', position: 'Center' } } { _id: { team: 'Cavs', position: 'Guard' } }
我们可以使用以下查询来查找团队、位置和积分字段的所有不同值:
db.teams.aggregate( [ { $group : {"_id": {team: " $team ", position: " $position ", points: " $points "}}} ] )
该查询返回以下文档:
{ _id: { team: 'Cavs', position: 'Guard', points: 33 } } { _id: { team: 'Rockets', position: 'Forward', points: 29 } } { _id: { team: 'Mavs', position: 'Guard', points: 22 } } { _id: { team: 'Rockets', position: 'Forward', points: 26 } } { _id: { team: 'Mavs', position: 'Guard', points: 31 } } { _id: { team: 'Rockets', position: 'Center', points: 19 } }
请注意,所有文档都会被返回,因为没有两个文档的 team、position和points 字段具有相同的值。
其他资源
以下教程解释了如何在 MongoDB 中执行其他常见操作: