Reputation: 1664
I looked on stack already and can't find the same problem as mine:
I have two collections: 1) users and 2) data.
users:
{
_id: "1234",
name: "John"
}
and data:
{
"userId":"1234",
"data": {
{...}
}
What I do now is I read all "data" documents and update the users collection for each users, to add the data (and perform more operations). It's a loop where for each data, I do a findOne() on user's Id, change the returned array.
Then, I save the new array in the users collection.
What I'd like is to do less call to Mongodb. My guess was to add every new "user" array in an array and at the end of my script, to send this array of users to Mongo. But I don't know how to tell him: "For each array in this array, update the collection."
Do you have any idea how to do that? Or maybe a better way to reach the same result?
I looked already on some question like How to update millions of documents independently? PHP + Mongo but the modification is only increases and aggregates, not like mine where I want to add a lot of data.
Upvotes: 0
Views: 605
Reputation: 65413
Assuming you are using MongoDB 2.6+ and a version of the MongoDB PHP driver newer than 1.5.0, you can take advantage of the Bulk Write API via the MongoInsertBatch
and MongoUpdateBatch
classes in the PHP driver.
Versions of MongoDB older than 2.6 support a more limited batch insert API (available in the PHP driver via MongoCollection::batchInsert()
).
The general strategy with bulk/batch inserts is to reduce network round trip time by sending multiple requests in a batch instead of individually.
Upvotes: 1