本文介绍了将元素插入到 MongoDB 中的嵌套数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 mongoDB 的新手.我在更新 mongoDB 集合中的记录时遇到了一些麻烦.

I am new to mongoDB. I am having some trouble in updating the records in mongoDB collection.

如何将元素添加到数组 likes 到嵌入的记录中

How to add elements into array likes into the embedded record

我有一个嵌入式集合,例如:

I have a embedded collection like:

{
  "_id": "iL9hL2hLauoSimtkM",
  "title": "Some Topic",
  "followers": [
    "userID1",
    "userID2",
    "userID3"
  ],
  "comments": [
    {
      "comment": "Yes Should be....",
      "userId": "a3123",
      "likes": [
        "userID1",
        "userID2"
      ]
    },
    {
      "comment": "No Should not be....",
      "userId": "ahh21",
      "likes": [
        "userID1",
        "userID2",
        "userID3"
      ]
    }
  ]
}

我想将记录更新为

{
  "_id": "iL9hL2hLauoSimtkM",
  "title": "Some Topic",
  "followers": [
    "userID1",
    "userID2",
    "userID3"
  ],
  "comments": [
    {
      "comment": "Yes Should be....",
      "userId": "a3123",
      "likes": [
        "userID1",
        "userID2",
        "userID3" // How to write query to add this element.
      ]
    },
    {
      "comment": "No Should not be....",
      "userId": "ahh21",
      "likes": [
        "userID1",
        "userID2",
        "userID3"
      ]
    }
  ]
}

请提供查询以添加评论中显示的元素.谢谢.

Please provide the query to add the element shown in comment.Thank you.

推荐答案

这里有两种可能:

  1. 由于您没有评论的唯一标识符,更新评论数组上特定项目的唯一方法是明确指出您要更新的索引,如下所示:

  1. Since you don't have an unique identifier for the comments, the only way to update an specific item on the comments array is to explicitly indicate the index you are updating, like this:

db.documents.update(
  { _id: "iL9hL2hLauoSimtkM"},
  { $push: { "comments.0.likes": "userID3" }}
);

  • 如果为评论添加唯一标识符,则可以搜索它并更新匹配的项目,而无需担心索引:

  • If you add an unique identifier for the comments, you can search it and update the matched item, without worrying with the index:

    db.documents.update(
      { _id: "iL9hL2hLauoSimtkM", "comments._id": "id1"},
      { $push: { "comments.$.likes": "userID3" }}
    );
    

  • 这篇关于将元素插入到 MongoDB 中的嵌套数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-28 08:15