【问题标题】:Select item from array of items in MongoDB [duplicate]从MongoDB中的项目数组中选择项目[重复]
【发布时间】:2020-09-08 12:52:57
【问题描述】:
 {
        "_id" : ObjectId("5ec0471dfec11a07d80c9d07"),
        "name" : "jasper",
        "posts" : [
                {
                        "_id" : ObjectId("5ec0473ffec11a07d80c9d08"),
                        "content" : "It,s all about........",
                        "title" : "THE NEEDY"
                },
                {
                        "_id" : ObjectId("5ec0475afec11a07d80c9d09"),
                        "content" : "I know..........",
                        "title" : "The world"
                }
        ],
        "__v" : 2
}

有很多用户,他们的数据以上述模式的形式存储在 MongoDB 中。我想更新任何内容(即考虑“我知道”)那么我应该如何使用 mongoose 来做到这一点? 首先我尝试获取 userId 并获取其全部数据,那么我应该如何选择帖子的 Id 并进行必要的更新?

感谢您的帮助

【问题讨论】:

    标签: arrays mongodb mongoose


    【解决方案1】:

    听起来你想使用arrayFilters

    看起来有点像:

    db.collection.updateOne(
        {_id: userId},
        {
            $set: {
                "posts.$[post].content": newContent,
            }
        },
        {arrayFilters: [{"post._id": postId}]}
    );
    

    【讨论】:

    • 感谢更新部分。你能告诉我如果我不想更新并且只是找到用户所说的哪个帖子 ID 怎么办?
    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    相关资源
    最近更新 更多