[英]Insert multiple documents in mongodb collection with a single insert statement using php
在 PHP 中,我有一些数据要插入。 示例数据如下所示
Array
(
[0] => Array
(
[uuid] => membership-60f929a1989d6960400020
[channel] => channel-594b9e3568ac3969784876
[user] => user-5b1e6e1b636e5325325732
[emailnotifications] => off
[email] => demo@xyz.com
)
[1] => Array
(
[uuid] => membership-60f929a198a1a549293025
[channel] => channel-594b9edcdea14894901526
[user] => user-5b1e6e1b636e5325325732
[emailnotifications] => off
[email] => demo@xyz.com
)
[2] => Array
(
[uuid] => membership-60f929a198a2b975658255
[channel] => channel-5ab261a60fe87688298186
[user] => user-5b1e6e1b636e5325325732
[emailnotifications] => off
[email] => demo@vizsafe.com
)
[3] => Array
(
[uuid] => membership-60f929a198a3b292013762
[channel] => channel-5e668d5522526659309093
[user] => user-5b1e6e1b636e5325325732
[emailnotifications] => off
[email] => demo@vizsafe.com
)
[4] => Array
(
[uuid] => membership-60f929a198a4a688473796
[channel] => channel-5e668d6fafbbe937126299
[user] => user-5b1e6e1b636e5325325732
[emailnotifications] => off
[email] => demo@vizsafe.com
)
)
我想将数组的每个元素作为单个文档插入。 例如 :-
Array (
[uuid] => membership-60f929a1989d6960400020
[channel] => channel-594b9e3568ac3969784876
[user] => user-5b1e6e1b636e5325325732
[emailnotifications] => off
[email] => demo@xyz.com
)
应作为单独的文件插入。 这应该使用单个插入语句来实现。 此外,正在使用的 mongodb 版本是 2.4,所以我不能使用 insertMany。 这能做到吗? 任何线索都会有所帮助。 感谢您提前回复。
更新
v2.4 是不可能的。
PHP mongo 驱动在 v1.5.0 中加入了批量插入,结合切换到mongodb v2.6 写协议:
它支持 MongoDB 2.6 的所有新功能,包括:
- 聚合现在可以返回一个游标
- 现在可以解释聚合管道
- 可以为命令和查询设置 maxTimeMS
- 对新的基于命令的 MongoDB 写入 API 的透明支持
- 新的 MongoWriteBatch 类(使用新的 MongoDB 写入 API)
上一个答案:
问题是关于遗留驱动程序https://pecl.php.net/package/mongo/1.5.1
您需要使用 MongoInsertBatch 插入多个文档。
来自https://www.php.net/manual/en/class.mongoinsertbatch.php (不再存在):
$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");
$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
$batch->add($document);
}
$retval = $batch->execute(array("w" => 1));
在你的情况下$collection
是$this->db->memberships
作为旁注,您确实需要升级堆栈。 它有十年的历史了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.