0

Here is a document(name is Word) example:

{
"id":"xxxxxxxx",
"words":["hello","world","cat","dog","word1","word2"]
}

now I have a word list contains some words, for example:

["friend","hello","world","stack","question"]

I have 2 operation (Every time I will do one of them, not all of them): 1. PUSH. I want to push all the new word into array, in this case ,the word is "friend","stack","question". "hello" and "world" is already exist, I will not push them in. 2. PULL. I want to pull some word already exist in words, in this case I want to pull "hello" and "world" out.

One way I know is to do a for loop, but it seems awful. Can I meet what I need in 1 update operation? such as collection.update(query,op).
I am using flask-MongoEngine and also pymongo operation is also supported.

McCree Feng
  • 179
  • 4
  • 12

2 Answers2

0

Try this one:

db.collection.aggregate([
   {
      $set: {
         words: {
            $setUnion: ["$words", ["friend", "hello", "world", "stack", "question"]]
         }
      }
   },
   {
      $set: {
         words: {
            $filter: {
               input: "$words",
               cond: { $not: { $in: ["$$this", ["hello", "world"]] } }
            }
         }
      }
   }
])

Mongo playground

NB, first adding "hello", "world" and then remove it afterwards looks pointless to me.

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
0
if you want to push unique data into array then you can use $addToSet:

let update = await userRepo.getAllNotificationUpdate(
   {$addToSet: {read_by:req.user._id}}
 );

if you want to pull data from array then you can use $pull. please check below url:

https://docs.mongodb.com/manual/reference/operator/update/pull/

Kuldeep Mishra
  • 3,846
  • 1
  • 21
  • 26