0

I have a document structure like this:

{
  _id: ...,
  name: ...,
  keywords: {
    group_a: [1, 2, 5],
    group_b: [4, 7, 6]
  }
}

I know I can add elements to one of the elements of the keywords object like this:

db.coll.update({_id: ...}, {
  $addToSet: {
    'keywords.group_a': {
      $each: [9, 12, 17]
    }
  }
})

Is there a command I can run to add the same set of elements to group_a and group_b? Something like

db.coll.update({_id: ...}, {
  $addToSet: {
    ['keywords.group_a', 'keywords.group_b']: {
      $each: [9, 12, 17]
    }
  }
})

which of course isn't valid.

I know the names of the groups in advance, but an "add them to all elements" solution is equally fine.

4

1 回答 1

0

You can affect multiple fields with a single $addToSet operator like so:

db.coll.update({_id: ...}, {
  $addToSet: {
    'keywords.group_a': {
      $each: [9, 12, 17]
    },
    'keywords.group_b': {
      $each: [9, 12, 17]
    }
  }
})

To keep it DRY you can, of course, do:

var each = { $each: [9, 12, 17] };
db.coll.update({_id: ...}, {
  $addToSet: {
    'keywords.group_a': each,
    'keywords.group_b': each
    }
  }
})
于 2012-11-22T16:42:36.833 回答