![](/img/trans.png)
[英]mongodb check if all subdocuments in array have the same value in one field
[英]MongoDB: Removing a field from ALL subdocuments in an array field
我有以下格式的數千份文件:
{
"_id" : ObjectId("51e98d196b01c2085c72d731"),
"messages" : [
{
"_id" : ObjectId("520167056b01c20bb9eee987"),
"id" : ObjectId("520167056b01c20bb9eee987"),
},
{
"_id" : ObjectId("520167056b01c20bb9eee988"),
"id" : ObjectId("520167056b01c20bb9eee988"),
},
{
"_id" : ObjectId("520167056b01c20bb9eee989"),
"id" : ObjectId("520167056b01c20bb9eee989"),
}
],
}
我需要刪除重復的“id”字段。 這是我嘗試過的:
db.forum_threads.update({}, {$unset: {"messages.$.id": 1}}, {multi: true});
這是我得到的錯誤:
Cannot apply the positional operator without a corresponding query field containing an array.
您收到該錯誤的原因是因為您在filter子句中沒有任何謂詞。 你可以這樣做:
mongos> db.test.update({"messages.id": {$exists: true}}, {$unset: {"messages.$.id":true}}, {multi:true})
並且您不會收到錯誤 - 實際上其中一個文檔將刪除id
屬性。 問題是位置運算符只匹配與謂詞匹配的數組的FIRST元素,它不匹配所有元素。 更大的問題是,目前無法在MongoDB中更新數組中的所有元素( https://jira.mongodb.org/browse/SERVER-1243 )。
你需要使用數字位置(“messages.0.id”,“messages.1.id”等)遍歷數組中的每個元素,或者你可以將數組拉入你的應用程序,循環遍歷元素並更新它們,然后將數組保存回來。
您可以從JIRA票證中看到此問題已經開放了很長一段時間,但10gen似乎並不認為它是非常高優先級。
使用Mongo 3.6,您可以使用新的位置標識符,並執行以下操作:
db.test.update({"messages.id": {$exists: true}}, {$unset: {"messages.$[].id":true}}, {multi:true})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.