Mongodb-删除嵌入文档中的一些数组元素 [英] Mongodb- Delete some of the array elements within embedded document

查看:81
本文介绍了Mongodb-删除嵌入文档中的一些数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种文件.类型 1.文档包含 MCN-ONE、MCN-TWO、MCN-THREE(或全部 3 个)以及其他值2. 另一种类型的文档不包含这些值中的任何值.首先,我想获取具有这些数组元素(1 个或 2 个或全部 3 个)的文档.然后我想保留 MCN-ONE、MCN-TWO、MCN-THREE 并批量删除所有其他(CCC-ALARM..etc).你能帮忙写下查询吗?下面提到的文件属于类型 1.

There are 2 kinds of documents. Type 1. Documents contain the either MCN-ONE, MCN-TWO, MCN-THREE(or all 3) along with other values 2. Another type of documents do not contain any among these values. First, I would like to get the documents having those array elements(either 1 or 2 or all 3). Then I want to keep MCN-ONE,MCN-TWO,MCN-THREE and delete all others (CCC-ALARM..etc) in bulk. Could you help to write the query? The below mentioned document falls in type 1.

{
"_id" : ObjectId("5d721f5296eaaafd1df263e8"),
"assetId" : "ALL",
"createdTime" : ISODate("2019-09-06T08:56:50.065Z"),
"default" : false,
"lastUpdatedTime" : ISODate("2019-09-06T09:11:35.463Z"),
"preferences" : {
    "MCN-TWO" : [ 
        "TEST"
    ],
    "MCN-ONE" : [ 
        "TEST", 
        "TEST", 
        "TEST"
    ],
    "MCN-THREE" : [ 
        "TEST"
    ],
    "CCC-ALARM" : [ 
        "TEST"
    ],
    "SSD-ALARM" : [ 
        "TEST"
    ],
    "TFT-ALARM" : [ 
        "TEST", 
        "TEST"
    ],
    "REC-WARN" : []
}
}

推荐答案

通用方法是使用 $objectToArray 转换 preferences 子文档,然后使用 $filter$map$reduce 并用 $arrayToObject 转换回来.但是,您的要求是获取元素 MCN-ONE、MCN-TWO、MCN-THREE".简单的方法是更新元素 preferences 并替换为 MCN-ONE,MCN-TWO,MCN-THREE 的内容.可以通过这个聚合来完成:

The generic approach would be to transform preferences subdocument with $objectToArray, then filter desired elements with $filter, $map or $reduce and transform back with $arrayToObject. However, your requirement is "get elements MCN-ONE,MCN-TWO,MCN-THREE". The simple way is to update element preferences and replace just with conten of MCN-ONE,MCN-TWO,MCN-THREE. It can be done by this aggregation:

为了过滤文档,设置$match阶段:

In order to filter documents, set the $match stage:

db.collection.aggregate(
   [
      {
         $match: {
            $expr: {
               $or: [
                  { $ne: ["$preferences.MCN-ONE", null] },
                  { $ne: ["$preferences.MCN-TWO", null] },
                  { $ne: ["$preferences.MCN-THREE", null] }
               ]
            }
         }
      },
      {
         $set: {
            preferences: {
               $mergeObjects: [
                  { "MCN-ONE": "$preferences.MCN-ONE" },
                  { "MCN-TWO": "$preferences.MCN-TWO" },
                  { "MCN-THREE": "$preferences.MCN-THREE" }
               ]
            }
         }
      }
   ]
)

这篇关于Mongodb-删除嵌入文档中的一些数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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