【问题标题】:Add new field to a specific object in mongoDB向 mongoDB 中的特定对象添加新字段
【发布时间】:2021-07-22 09:11:21
【问题描述】:

我想在搜索特定对象后向对象添加一个新字段, 数据库如下所示:

{
    "_id": {
        "$oid": "608378ef1ae6b1368c6220c6"
    },
    "username": "paul",
    "password": "cacavaca123",
    "question": "q1",
    "answer": "cutu"
}
{
    "_id": {
        "$oid": "6084c1b557f2242bcc629440"
    },
    "username": "mircea",
    "password": "123456",
    "question": "q1",
    "answer": "cutu"
}

我想在数据库中搜索具有 username:paul 的对象并添加一个新字段 friends:[alex],我已经尝试过了,但它不起作用:

MongoClient.connect(uri, function(err, db) {
        var dbc = db.db("chat");
        dbc.collection("accounts").find({username: { $eq: user}}).aggregate( [
            {
              $addFields: {
                frequent:[new_friend]
              }
            }
        ])

        db.close();
    });

另外,如果您知道,您能告诉我如何更新 朋友 数组并将新朋友添加到该数组吗?

【问题讨论】:

    标签: node.js database mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你必须使用更新查询来这样做

    阅读 - updateOne

    演示 - https://mongoplayground.net/p/mrTg0DKtnrW

    db.collection.update(
    { "username": "paul" },
    {
      $set: {
        friends: ["alex" ]
      }
    })
    

    聚合演示 - https://mongoplayground.net/p/yiJgkrgdeHZ

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-22
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多