0

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" : []
}
}

1 Answer 1

1

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:

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" }
               ]
            }
         }
      }
   ]
)
Sign up to request clarification or add additional context in comments.

9 Comments

Can you explain this query.?
Thanks for the explanation. Looks I have not explained properly my use case.Updated the question.
According to what you have asked, the solution is still the same.
But i suspect, the above query would update the type 2 documents as well which i don't want to touch. Am i wrong here?
See my answer. $set was added in MongoDB 4.2, use $addFields instead.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.