【问题标题】:Try to use $pull but get error "Cannot apply $pull to a non-array value"尝试使用 $pull 但出现错误“无法将 $pull 应用于非数组值”
【发布时间】:2021-05-06 09:54:37
【问题描述】:

我有以下文件:

{
"_id": "608ab562870b912adac9c410",
 "drt": {
       "templates": [{
            "shop_template_id": "6092923793bcfa950d05a3d5",
            "created_at": "2021-05-05T19:19:12.689Z",
            "template_name": "V28",
            "content": "aaa"
          }]
     }
}

当我尝试使用以下查询将其删除时出现问题:

db
.collection('books')
.updateMany(
    { _id: new ObjectID(id)},
    { $pull: {drt: {templates: {shop_template_id: new ObjectID(templateId)}}}},
    { multi: true }
)

我收到此错误消息:"Cannot apply $pull to a non-array value"

我做错了什么?谢谢!

【问题讨论】:

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


    【解决方案1】:

    您需要对嵌套字段使用点表示法:

    {
        $pull: {
            "drt.templates": {
                shop_template_id: ObjectId("6092923793bcfa950d05a3d5")
            }
        }
    }
    

    Mongo Playground

    【讨论】:

    • 谢谢老兄,我没注意到!!现在它完美运行!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2015-07-04
    • 2012-10-23
    • 1970-01-01
    • 2021-05-14
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多