Pull and addtoset at the same time with mongo

前端 未结 4 2036
别那么骄傲
别那么骄傲 2020-12-01 14:21

I have a collection which elements can be simplified to this:

{tags : [1, 5, 8]}

where there would be at least one element in array and all of t

4条回答
  •  佛祖请我去吃肉
    2020-12-01 14:33

    If you're removing and adding at the same time, you may be modeling a 'map', instead of a 'set'. If so, an object may be less work than an array.

    Instead of data as an array:

    { _id: 'myobjectwithdata',
      data: [{ id: 'data1', important: 'stuff'},
             { id: 'data2', important: 'more'}]
    }
    

    Use data as an object:

    { _id: 'myobjectwithdata',
      data: { data1: { important: 'stuff'},
              data2: { important: 'more'} }
    }
    

    The one-command update is then:

    db.coll.update(
      'myobjectwithdata', 
      { $set: { 'data.data1': { important: 'treasure' } }
    );
    

    Hard brain working for this answer done here and here.

提交回复
热议问题