我正在接收和存储JSON对象数组,如下所示:
$json_assoc_array = array (
{
'id' => "unique-id-1",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
},
{
'id' => "unique-id-2",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
},
{
'id' => "unique-id-3",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
}
);
然后我将以相同的格式接收这些对象的更新。我需要通过它们的id
字段来更新对象/文档。
当我使用简单的insertMany
将它们插入MongoDB时,它们还会获得唯一的MongoDB对象_id
s,因此生成的文档如下所示:
$json_assoc_array = array (
{
'_id' => "5b824c113e2ffc4e7239bfc5"
'id' => "unique-id-1",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
},
{
'_id' => "5b824c1b3e2ffc4e7239caa2"
'id' => "unique-id-2",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
},
{
'_id' => "5b824c1b3e2ffc4e7239caa3"
'id' => "unique-id-3",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
}
);
永远不会有ID为unique-id-1
的其他文档。因此,我现在要在最初插入它们之前对其进行设置,如下所示:
$json_assoc_array = json_decode($data, true);
// Set order MongoDB _id
$json_assoc_array['_id'] = $json_assoc_array['id'];
// Set MongoDB collection
$collection = $mongo->mongo_db_name->collection;
// Insert documents into MongoDB
$result = $collection->insertMany( $json_assoc_array );
// Now when I insert the above documents, they result in this
$json_assoc_array = array (
{
'_id' => "unique-id-1"
'id' => "unique-id-1",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
},
{
'_id' => "unique-id-2"
'id' => "unique-id-2",
'key_one' => "some value",
'key_two' => "some value",
'key_three' => "some value"
},
...
);
有什么不好的做法吗?
我是否应该保留_id
由MongoDB设置,并使用id
字段来更新现有文档?
答案 0 :(得分:1)
除了_id
is immutable以外,您还可以使用数组条形图。
这甚至可能对您有利。使用精心设计的索引和查询,您也许可以从index intersections (more than one index being used in a query)中受益。它本身为您提供了更多选项来有效地对数据建模,但是现在让我们将这方面放在一边。更有趣的一点是,如果您只需要索引覆盖的文档字段的子集,则可以利用以下方法进行相应的查询“ covered”(仅从通常保存在RAM中的索引进行回答)您无法避免的索引。
tl; dr:ObjectId仅仅是一种构造,能够在您的数据不提供全局唯一标识符的情况下提供全局唯一标识符。我个人认为最佳做法是使用具有语义价值的东西代替ObjectId。