如何在MongoDB中从多个字段中选择不同的值

103 阅读1分钟

你可以使用以下语法从MongoDB的多个字段中选择不同的值:

db.collection.aggregate( 
            [
                {$group: { "_id": { field1: "$field1", field2: "$field2" } } }
            ]
        )

下面的例子展示了如何用一个带有以下文件的集合队来使用每个方法:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})

例子:从多个字段中选择不同的值

我们可以使用下面的查询来从团队和职位字段中找到所有的不同值:

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 } }

请注意,所有的文件都被返回,因为没有两个文件的团队、位置积分字段的值是相同的。

其他资源

下面的教程解释了如何在MongoDB中执行其他常见操作:

MongoDB:如何在集合中添加新字段
MongoDB:如何按分组和计数
MongoDB:如何按多个字段分组