gpt4 book ai didi

mongodb - 将元素插入到 MongoDB 中的嵌套数组中

转载 作者:IT老高 更新时间:2023-10-28 13:31:47 24 4
gpt4 key购买 nike

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

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

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

{
"_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"
]
}
]
}

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

最佳答案

这里有两种可能性:

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

    db.documents.update(
    { _id: "iL9hL2hLauoSimtkM"},
    { $push: { "comments.0.likes": "userID3" }}
    );
  2. 如果为评论添加唯一标识符,则可以搜索并更新匹配项,而无需担心索引:

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

关于mongodb - 将元素插入到 MongoDB 中的嵌套数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36113069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com