【发布时间】:2016-12-19 09:08:57
【问题描述】:
我最近开始研究 Mongo db。 这是我在数据库 homeconfig 和集合 data
中的 mongo db 中的示例文档{
"_id": {},
"user_id": "user",
"rooms": [
{
"name": "abhi",
"metadata": {
"user_id": "user",
"is_expired": "false",
"expired_on": null
}
}
],
"sections": [
{
"name": "section1",
"metadata": {
"user_id": "user",
"room": "abhi",
"is_expired": "false",
"expired_on": null
}
}
],
"devices": [
{
"id": "aur.01.Jpzp0o",
"metadata": {
"section_less": "true",
"label": "aa",
"is_active": null,
"is_loading": null,
"is_dimmable": null,
"type": "aura",
"sub_device": "aur.01",
"is_favourite": "false",
"dimming": null,
"energy_usage": 0,
"usage_today": 0,
"avg_usage": 0,
"ir_control": null,
"user_id": "user",
"room": "abhi",
"section": null,
"is_expired": "false",
"expired_on": null
}
}
]
}
上面显示的 JSON 只是我的文档的一个示例。实物很大,我不能透露原件。
下面是我用来更新文档中集合的函数。
function removeSectionsFromMongo($user_id, $data, $date)
{
$collection = (new MongoConnect())->connect('homeconfig', 'data');
foreach ($data as $key ) {
$update = $collection->updateOne(['user_id'=>$user_id, 'sections' => ['$elemMatch' => ['name' => $key['name'], 'metadata.is_expired' => 'false' ]]],
['$set'=>['sections.$.metadata.is_expired'=>'true', 'sections.$.metadata.expired_on'=>$date]]
);
if($update->getModifiedCount() == 1)
{
echo "Section <".$key['name']."> removed from room <".$key['metadata']['room'].">."."\n";
}
}
}
变量$data是一个如下所示的数组:
Array
(
[0] => Array
(
[name] => Appliances
[metadata] => Array
(
[user_id] => CubicalPrime
[room] => Dhruv
[is_expired] => false
[expired_on] =>
)
)
[1] => Array
(
[name] => Bathroom
[metadata] => Array
(
[user_id] => CubicalPrime
[room] => Dhruv
[is_expired] => false
[expired_on] =>
)
)
[2] => Array
(
[name] => Others
[metadata] => Array
(
[user_id] => CubicalPrime
[room] => Dhruv
[is_expired] => false
[expired_on] =>
)
)
)
当我执行该函数时,它应该更新我的文档中的所有sections 匹配数组$data 传递。
但是,它正在更新文档。但是当文档的大小增加时,sections 中的一些对象有时没有得到更新。即 is_expired 字段未更新为 true 和 expired_on 未在已过的日期内更新。
当我再次运行相同的函数时,整个更新将在第二次发生。
只有当查询结果显示修改计数等于 1 时,我才会回显。这意味着查询正在正确执行。但是很少有文档没有得到更新。
if($update->getModifiedCount() == 1)
{
echo "Section <".$key['name']."> removed from room <".$key['metadata']['room'].">."."\n";
}
我正在试图弄清楚为什么文档第一次没有得到更新,但第二次得到了更新!!
帮我看看我的代码有什么问题?
【问题讨论】: