我在MongoDB中有一个名为job
的集合 Job{
_id : ‘12344’,
cust_id: 'cust1',
title: 'Create Website',
description: 'We require it in 2 weeks only',
location: 'japan',
images:{
'image1',
'image2',
'image3'
},
video:{
'video1',
'video2'
},
budget:'15000',
duration:'2 weeks',
Proposals:[{
"sender_id" => "5",
"description" =>"I can do your task before 2 week",
"date" => "2013-08-05"
},
{
"sender_id" => "6",
"description" =>"I can do your task in 2 week, with best quality",
"date" => "2013-08-05"
}
]
}
我想在投标属性中添加邮件,其sender_id = 5,如下所示;
Job{
_id : ‘12344’,
cust_id: 'cust1',
title: 'Create Website',
description: 'We require it in 2 weeks only',
location: 'japan',
images:{
'image1',
'image2',
'image3'
},
video:{
'video1',
'video2'
},
budget:'15000',
duration:'2 weeks',
Proposals:[{
"sender_id" => "5",
"description" =>"I can do your task before 2 week",
"date" => "2013-08-05"
“messages”:[{
"message_sender" :"Can we meet",
"date" : "2013-08-06"
}
]
},
{
"sender_id" => "6",
"description" =>"I can do your task in 2 week, with best quality",
"date" => "2013-08-05"
}
]
}
我的文件是,
$document = array(
"message_sender" =>"Can we meet",
"date" => "2013-08-06"
);
我真的很难做这件事。这是向提议数组添加消息。有PHP代码的帮助吗?
答案 0 :(得分:2)
这对我来说是完美的答案,
db.jobs.update({"_id" : "12344","Proposals.sender_id":"5"},{$push:{"Proposals.$.messages" : { "message" : "Can we meet" , "date":"2013-08-06"}}})
答案 1 :(得分:0)
通常当遇到这样的复杂问题时,这意味着您需要将子文档拆分为真正的顶级文档 - 可能会分成不同的集合。在这种情况下,你肯定需要将Proposals推送到他们自己的集合中,你需要更改你的_id并添加一个job_id来引用回真正的工作:
{
"_id" => …,
"job_id" => 12344,
"sender_id" => "5",
"description" =>"I can do your task before 2 week",
"date" => "2013-08-05"
},
{
"_id" => …,
"job_id" => 12344,
"sender_id" => "6",
"description" =>"I can do your task in 2 week, with best quality",
"date" => "2013-08-05"
}
然后,您可以使用以下命令将新消息推送到数组中:
$document = array(
"message_sender" =>"Can we meet",
"date" => "2013-08-06"
);
$collection->update(
array( 'job_id' => 12344, 'sender_id' => "5" ),
array( 'messages' => array( '$push' => $document ) )
);
确保您在job_id, sender_id
上创建索引:
$collection->ensureIndex( array( 'job_id' => 1, "sender_id" => 1 ) );