MongoDB替换特定的数组值 [英] MongoDB Replace specific array values

查看:640
本文介绍了MongoDB替换特定的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中,我有一个电影收藏,其中包含多种语言,例如
languages: [0:USA, 1: German, 2: French, ...etc]

In MongoDB, I have a movie collection that has an array of languages , e.g.
languages: [0:USA, 1: German, 2: French, ...etc]

数组值没有任何特定顺序.

The array values are not in any particular order.

现在如何基于某些特定值更新数组值?假设我要更新所有法语"并将整个集合替换为"Francais".我该怎么办?

How can I now update an array value based on some specific value? Let's say I want to update all "French" and replace it with "Francais" for the entire collection. How can I do that?

推荐答案

使用位置$运算符,它标识languages数组中要更新的元素,而无需显式指定其在数组中的位置,即代替预先知道位置并将元素更新为:

Use the positional $ operator which identifies the element in the languages array to update without explicitly specifying its position in the array i.e. instead of knowing the position in advance and updating the element as:

db.movies.updateMany(
    { "languages": "French" }, 
    { "$set": { "languages.2": "Francais" } }
)

您可以只使用 $ 运算符为:

you can just use the $ operator as:

db.movies.updateMany(
    { "languages": "French" }, 
    { "$set": { "languages.$": "Francais" } }
)

这篇关于MongoDB替换特定的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆