首页 > 解决方案 > 如何在 mongodb 集合内的数组字段中插入值?

问题描述

我想在 mongodb 集合中存在的字符串数组中插入一个字符串。集合看起来像:

{
   "_id": some id,
   "urls": [url1,url2]
}

我想在对 urls 数组的每个插入调用中插入一个字符串我该怎么做?

标签: databasemongodbhttppostnosql

解决方案


操作员在$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});

推荐阅读