【问题标题】:How to insert a value in an array field inside mongodb collection?如何在 mongodb 集合内的数组字段中插入值?
【发布时间】:2020-10-10 05:25:05
【问题描述】:

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

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

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

【问题讨论】:

  • 不清楚您所说的“插入对 urls 数组的调用”是什么意思。例如,你想把[url1,url2] 变成[url1,newInsertString,url2]吗?
  • 是的,只有那个..

标签: database mongodb http post nosql


【解决方案1】:

$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" ] }

请注意,位置也可以是负数。 -1 是数组的末尾,-2 是从末尾开始的 1 项,等等。要在每个文档的 items 数组中插入一些内容,请提供 {} 谓词和 multi:true 选项:

db.foo.update({},{$push: {"items": {$each: ["foo","bar"], $position: 1}}},{multi:true});

【讨论】:

    【解决方案2】:

    您的 post 请求(例如 express.js)将如下所示:

    const urlRouter = express.Router();
    urlRouter.route('/your_route_here').post((req, res, next) => {
        yourMongoCollectionSchema.create(req.body)
        .then(url => {
            console.log("Url added", url);
            res.setHeader('Content-Type', 'application/json');
            res.json(url);
        }, err => next(err))
        .catch(err => next(err));
    })
    

    【讨论】:

      猜你喜欢
      • 2017-12-29
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 2011-07-19
      • 2015-07-24
      相关资源
      最近更新 更多