Reputation: 3832
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
¨?
Upvotes: 0
Views: 259
Reputation: 151132
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.
Upvotes: 3