MongoDB
 SQL >> Datenbank >  >> NoSQL >> MongoDB

Element per $push an eine bestimmte Array-Position in MongoDB anhängen

Der positionsabhängige $-Operator funktioniert nur, wenn das Array-Feld auch in der Query vorkommt.

MySchema.findOneAndUpdate(
  { "_id": questionId, "question.answers.author": "patrick" },
  { "$push": { "question.answers.$.comments": { "$each": [comment] } } },
  function (err, doc) { /* ... */ }
);

Wenn der Index bekannt ist, kann man ihn direkt adressieren:

{ "$push": { "question.answers.1.comments": { "$each": [comment] } } }