如何在MongoDB中使用all位置操作符来更新一个数组中的所有元素

85 阅读1分钟

关于MongoDB的全面概述和我所有关于它的帖子,请查看我的概述

MongoDB提供了一个特殊的更新操作符$[] ,将更新操作应用于一个数组中属于匹配文档的所有元素。

以下面的数据插入到一个叫做games 的集合中:

db.games.insertMany(
	{
		name: "Genshin Impact",
		reviewScores: [8, 6, 9, 5]
	},
	{
		name: "Factorio",
		reviewScores: [7, 7, 10, 8]
	},
	{
		name: "Bloodborne",
		reviewScores: [9, 8, 9, 9]
	}
)

对于每个评论中没有10分的游戏,将所有的评论分数增加1:

db.games.updateMany(
	{ reviewScores: { $ne: 10 } },
	{ $inc: { "reviewScores.$[]": 1 } }
)

使用find方法将所有数据读回,以查看结果:

{
	name: "Genshin Impact",
	reviewScores: [9, 7, 10, 6]
},
{
	name: "Factorio",
	reviewScores: [7, 7, 10, 8]
},
{
	name: "Bloodborne",
	reviewScores: [10, 9, 10, 10]
}

相关