MongoDB:从数组字段中的所有子文档中删除字段 [英] MongoDB: Removing a field from ALL subdocuments in an array field

查看:576
本文介绍了MongoDB:从数组字段中的所有子文档中删除字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有成千上万种采用这种格式的文档:

I have thousands of documents in this format:

{
"_id" : ObjectId("51e98d196b01c2085c72d731"),
"messages" : [
    {
        "_id" : ObjectId("520167056b01c20bb9eee987"),
        "id" : ObjectId("520167056b01c20bb9eee987"),

    },
    {
        "_id" : ObjectId("520167056b01c20bb9eee988"),
        "id" : ObjectId("520167056b01c20bb9eee988"),

    },
    {
        "_id" : ObjectId("520167056b01c20bb9eee989"),
        "id" : ObjectId("520167056b01c20bb9eee989"),
    }
],
}

我需要删除重复的"id"字段.这是我尝试过的:

I need to remove the duplicate "id" field. This is what I have tried:

db.forum_threads.update({}, {$unset: {"messages.$.id": 1}}, {multi: true});

这是我得到的错误:

Cannot apply the positional operator without a corresponding query field containing an array.

推荐答案

出现该错误的原因是因为filter子句中没有任何谓词.您可以这样做:

The reason you're getting that error is because you don't have any predicate in the filter clause. You can do this:

mongos> db.test.update({"messages.id": {$exists: true}}, {$unset: {"messages.$.id":true}}, {multi:true})

您将不会收到错误-实际上其中一个文档将删除id属性.问题在于位置运算符仅匹配与谓词匹配的数组的FIRST元素,而不匹配所有元素.更大的问题是,当前无法在MongoDB中更新数组中所有元素( https://jira.mongodb. org/browse/SERVER-1243 ).

And you won't get an error - in fact one of the documents will have the id attribute removed. The problem is that the positional operator only matches the FIRST element of the array that matches your predicate, it doesn't match all elements. The bigger issue is that it's not currently possible to update all the elements in an array in MongoDB (https://jira.mongodb.org/browse/SERVER-1243).

您要么需要使用数字位置("messages.0.id","messages.1.id"等)遍历数组中的每个元素,要么可以将数组拉入您的应用程序,遍历元素并更新它们,然后将数组保存回去.

You'll either need to iterate through each element in the array using the numerical position ("messages.0.id", "messages.1.id", etc.) or you can pull the array into your application, loop through the elements and update them, and then save the array back out.

您可以从JIRA票证中看到,此问题已经开放了一段时间,但是10gen似乎并不认为它具有很高的优先级.

You can see from the JIRA ticket that this issue has been open for quite awhile but 10gen doesn't seem to consider it very high priority.

这篇关于MongoDB:从数组字段中的所有子文档中删除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆