database - 如何在 mongodb 集合内的数组字段中插入值?
问题描述
我想在 mongodb 集合中存在的字符串数组中插入一个字符串。集合看起来像:
{
"_id": some id,
"urls": [url1,url2]
}
我想在对 urls 数组的每个插入调用中插入一个字符串我该怎么做?
解决方案
操作员在$push
一段时间前进行了更改,以允许将 1 到 n 个项目的数组插入到任意位置的现有数组中:
db.foo.find();
{ "_id" : 0, "items" : [ "url1", "url2" ] }
// Position starts at 0. Let's use position 1 for the demo:
db.foo.update({_id:0},{$push: {"items": {$each: ["foo","bar"], $position: 1}}});
db.foo.find();
{ "_id" : 0, "items" : [ "url1", "foo", "bar", "url2" ] }
请注意,位置也可以是负数。items
-1 是数组的末尾,-2 是从末尾开始的 1 项,等等。要在每个文档的数组中插入一些内容,请提供{}
谓词和multi:true
选项:
db.foo.update({},{$push: {"items": {$each: ["foo","bar"], $position: 1}}},{multi:true});
推荐阅读
- java - java中调用thread.start()后的语句流程是什么?
- xml - id 函数和无效 xml:id 属性的不同结果
- python - Pytorch:如何在二维张量的每一行中找到第一个非零元素的索引?
- python - mlflow 找不到 .py 文件
- javascript - 如何使用 post 方法向服务器发送值?
- c# - 当我调用 new Microsoft.Office.Interop.Word.Application() 时如何修复异常
- ruby-on-rails - 带有数组字段的 GraphQL ObjectType 返回 null
- r - 为什么数字有时被视为 R 中的字符?
- php - 语法错误,意外的“?” 在我的 laravel 应用中
- android - Google Play 商店中不支持的 API 警告