title: Remove all items from an array NOT in array in MongoDB
body: <p>I have two collections in Mongo. For simplification I´m providing a minified example</p>
  
  <p><strong>Template Collection:</strong></p>
  
  <pre><code>{
     templateId:0,
     values:[
        {data:"a"},
        {data:"b"},
        {data:"c"}
        {data:"e"}
     ]
  }
  </code></pre>
  
  <p><strong>Data Collection:</strong></p>
  
  <pre><code>{
     dataId:0,
     templateId:0,
     values:[
        {data:"a",
        value: 10},
        {data:"b",
        value: 120},
        {data:"c",
        value: 3220},
        {data:"d",
        value: 0}
     ]
  }
  </code></pre>
  
  <p>I want to make a sync from <strong>Template Collection -> Data Collection</strong>, between the template 0 and all documents using that template. In the case of the example, that would mean:</p>
  
  <ol>
  <li>Copy {data:"e"} into the arrays of all documents with the templateId: 0</li>
  <li>Remove {data:"d"} from the arrays of all documents with the templateId: 0</li>
  <li>BUT do not touch the rest of the items. I can´t simply replace the array, because those values have to be kept</li>
  </ol>
  
  <p><strong>I´ve found a solution for 1.</strong></p>
  
  <p>db.getCollection('data').update({templateId:0},
           {$addToSet: {values: {
              $each:[ 
                 {data:"a"},
                 {data:"b"},
                 {data:"c"}
                 {data:"e"} 
              ]
              }}}, {
                  multi: true}
                  )</p>
  
  <p><strong>And a partial solution for 2.</strong></p>
  
  <p>I got it. First tried with $pullAll, but the normal $pull seems to work together with the $nin operator</p>
  
  <pre><code>db.getCollection('data').update({templateId:"QNXC4bPAF9J6r9FQu"},
           {$pull:{values: { $nin:[ 
               {data:"a"},
               {data:"b"},
               {data:"c"}
               {data:"e"}]
              }}}, {
                  multi: true}
                  )
  </code></pre>
  
  <p>This will remove <strong>{data:"d"}</strong> from all document arrays, but it seems to <strong>overwrite</strong> the complete array, and this is not what I want, as those <strong>value</strong> entries need to be persisted</p>
  
  <p>But how can I perform a query like <strong>Remove everything from an array EXCEPT/NOT IN [a,b,c,d,...]</strong> ?</p>