Mongodb 使用其他字段的值更新字段
如何使用其他字段的值更新字段? 例如,我想用创建的字段的值更新更新更新的字段(就像克隆字段一样) 谢谢选项#1:应用程序端更新 使用Doctrine ODM时最简单的方法是在应用程序端执行更新。因此,您可以获取所有要更新的对象,进行必要的调整并刷新它们Mongodb 使用其他字段的值更新字段,mongodb,symfony,doctrine-orm,query-builder,odm,Mongodb,Symfony,Doctrine Orm,Query Builder,Odm,如何使用其他字段的值更新字段? 例如,我想用创建的字段的值更新更新更新的字段(就像克隆字段一样) 谢谢选项#1:应用程序端更新 使用Doctrine ODM时最简单的方法是在应用程序端执行更新。因此,您可以获取所有要更新的对象,进行必要的调整并刷新它们 $services = $dm->createQueryBuilder('MyBundle:MyService') ->getQuery() ->execute(); foreach ($services as
$services = $dm->createQueryBuilder('MyBundle:MyService')
->getQuery()
->execute();
foreach ($services as $service) {
$service->setUpdatedAt($service->getCreatedAt());
}
$db->flush();
$services
表示mongo光标,它将在您迭代时获取文档。如果要一次从集合中获取所有文档,可以将cursor
设置为true
选项2:数据库端更新
还可以直接在数据库本身上执行更新。但是,要执行此操作,您需要自己创建查询,因为查询生成器不支持此功能
// Get MongoDB instance from DocumentManager
$mongo = $dm->getDocumentDatabase('Fully/Qualified/Class/Name')
->getMongoDB();
// Iterate over the collection and update each document
$mongo->execute('
db.MyServiceCollection.find().forEach(function (item) {
db.MyServiceCollection.update(
{_id: item._id},
{$set: {updated_at: item.created_at}}
);
});
');
forEach
中使用的函数只是一个常规的javascript函数,因此如果您需要对更新内容进行更多控制,可以在其中插入更多的逻辑。可能使用聚合??
// Get MongoDB instance from DocumentManager
$mongo = $dm->getDocumentDatabase('Fully/Qualified/Class/Name')
->getMongoDB();
// Iterate over the collection and update each document
$mongo->execute('
db.MyServiceCollection.find().forEach(function (item) {
db.MyServiceCollection.update(
{_id: item._id},
{$set: {updated_at: item.created_at}}
);
});
');