我想要集合命名系统,其中有一个名为sub_systems的文档,其中有三个文件名为high mid&低。每个高,中,低都包含单独的多个文档,如下所示
systems: {
sub_system_1 : {
high :{ {task1},
{task2},
.......
},
mid :{ {task1},
{task2},
.......
},
low :{ {task1},
{task2},
.......
},
},
sub_system_2 : {
high :{ {task1},
{task2},
.......
},
mid :{ {task1},
{task2},
.......
},
low :{ {task1},
{task2},
.......
},
},
............
}
以下是我遇到的问题 1.我将如何创建这样的嵌套文档。 2.如何在系统集合中插入新的子系统。 3.如何在子系统文档下插入新的优先级(高,中,低)。 4.如何在特定子系统和特定优先级(高,低,中)文档中插入新任务
我想知道使用mongo shell和perl mongodb
答案 0 :(得分:3)
db.systems.insert( [{"name": "sub_system_1", "data" : {"high" :["task1","task2"], "mid": ["task1","task2"], "low" : ["task1","task2"]}},{"name": "sub_system_2" ,"data": {"high" :["task1","task2"], "mid": ["task1","task2"], "low" : ["task1","task2"]}}])
db.systems.insert( {"name": "sub_system_3", "data" : {"high" :["task1","task2"], "mid": ["task1","task2"], "low" : ["task1","task2"]}})
// First you need to find the document using the name field
var sub_system_1 = db.systems.findOne({"name":"sub_system_1"})
// set your new priority
sub_system_1.data.new_priority = [ "task1", "task2" ]
// Save updated document
db.systems.save(sub_system_1)
您也可以使用updateOne调用在一个语句中进行更新,请参阅以下文档 https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/#db.collection.updateOne
// First you need to find the document using the name field
var sub_system_1 = db.systems.findOne({"name":"sub_system_1"})
// Now we add a new task to priority low
sub_system_1.data.low[sub_system_1.data.low.length] = "task3"
// Save updated document
db.systems.save(sub_system_1)
#!/usr/bin/perl
use MongoDB::Connection;
my $mongodb_dbhost = 'mongodb.co.za';
my $mongodb_dbname = 'systems_production';
my $mongodb_dbtable = 'systems';
my $connection = MongoDB::Connection->new(host => $mongodb_dbhost);
my $collection = $connection->$mongodb_dbname->$mongodb_dbtable;
my $data = $collection->insert( [
{
"name": "sub_system_1", "data" : {"high" :["task1","task2"], "mid": ["task1","task2"], "low" : ["task1","task2"]}
},
{
"name": "sub_system_2" ,"data": {"high" :["task1","task2"], "mid": ["task1","task2"], "low" : ["task1","task2"]}
}
]);
$data = $collection->insert({
"name": "sub_system_3",
"data" : {"high" :["task1","task2"], "mid": ["task1","task2"], "low" : ["task1","task2"]}
});
my $sub_system_1 = $connection->$mongodb_dbname->$mongodb_dbtable->find_one({'name' => 'sub_system_1'});
$sub_system_1->{data}->{new_priority} = [ "task1", "task2" ];
$collection->save($sub_system_1);
my $sub_system_1 = $connection->$mongodb_dbname->$mongodb_dbtable->find_one({'name' => 'sub_system_1'});
$sub_system_1->{data}->{low}->[scalar(@$sub_system_1->{data}->{low})] = "task3";
$collection->save($sub_system_1);