0

Im using Mongodb with Mongoskin. I have the following data structure:

clients: {
  firstArray: [
    {
      _id: '153'.
      someField1: 'someVal1',
      someField2: 'someVal2'
    }
    ...
  ]

  secondArray: [
    {
      _id: '7423'.
      someField1: 'someVal1',
      someField2: 'someVal2',
      firstArrayIds: ['153, 154, 155, ...']
    }
    ...
  ]
}

Is it somehow possible to $push a object to firstArray, and in the same query add the _id to secondArray.firstArraysIds¨?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Anders Östman
  • 3,702
  • 4
  • 26
  • 48

1 Answers1

3

Who said you can't do this? It''s pretty simple as $push is a "top level" update modifier, and as such takes a "document level" argument case:

db.collection.update(
    { "_id": someDocumentId, "secondArray._id": 7423 },
    {
       "$push": {
           "firstArray": someNewObject,
           "secondArray.$.firstArrayIds": someNewObject._id
       }
    }
);

So the positional $ operator allows you to update the element of "secondArray" that matched your condition.

The only thing you cannot do is match the elements of more than one array element in the document and ask for those "positions" to be updated. As the documentation says, only the first match index will be stored for the positional operator.

But in what you are asking to do, which requires a single match only then this is fine.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • Thanks Neil. I was expecting you to know this instantly =) – Anders Östman Sep 24 '14 at 12:06
  • @AndersÖstman Most of the reason I got onto stackoverflow this year, and eesentially to provide reasonably explanations to common operations or even complex problems that were not provided before. Even submitted various documentation patches, and though well received, there has been a move in the company to employ interns to re-vamp the documentation with clearer examples. Meh. I suppose I should blog more really. – Neil Lunn Sep 24 '14 at 12:14
  • I had a feeling I somehow should get into trouble with this. Please see this question: http://stackoverflow.com/questions/26165650/mongodb-pull-syntax. I really appreciate all you help! – Anders Östman Oct 02 '14 at 16:53