Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在mongodb中插入带有引用文档的文档_Mongodb - Fatal编程技术网

如何在mongodb中插入带有引用文档的文档

如何在mongodb中插入带有引用文档的文档,mongodb,Mongodb,我有两份文件: Contry { code : integer name: string } 及 我这样做是为了插入该国的一个州和一个州(使用mongo shell): 这是正确的吗 有更好的方法吗?来自: MongoDB应用程序使用以下两种方法之一来关联文档: Contry { code : integer name: string } 将一个文档的_id字段保存到另一个文档中作为引用。然后,应用程序可以运行第二个查询以返回相关数据。这些引用对于大多数用例

我有两份文件:

Contry {
    code : integer
    name: string
}

我这样做是为了插入该国的一个州和一个州(使用mongo shell):

这是正确的吗

有更好的方法吗?

来自:

MongoDB应用程序使用以下两种方法之一来关联文档:

Contry {
    code : integer
    name: string
}
  • 将一个文档的_id字段保存到另一个文档中作为引用。然后,应用程序可以运行第二个查询以返回相关数据。这些引用对于大多数用例来说都是简单和足够的

  • 是从一个文档到另一个文档的引用,使用第一个文档的_id字段的值、集合名称以及(可选)其数据库名称。通过包含这些名称,DBREF允许位于多个集合中的文档更容易与单个集合中的文档链接

在这里,由于您的国家/地区代码始终与
country
集合中的条目相关,因此不需要DBRef。此外,如果我假设
code
是唯一的键(这是您的
\u id
?),您可以简单地使用:

db.country.insert({ code : 1, name: 'Brasil' });
db.state.insert({ code : 1, state: 'SC', country: 1 });
//                                                ^
//                                  a reference to country with code 1
也就是说,根据您的用例,使用适当的方法可能是一个更好的主意:

oid = ObjectId()
db.country.insert({ _id: oid, code : 1, name: 'Brasil' });
db.state.insert({ code : 1, state: 'SC', country: oid });
使用以下方法解决:

var countryId = Object();
db.country.insert({ _id: countryId, code: 1, name: 'Brasil' });
db.state.insert({ code: 1, name: 'SC', contry : { $ref: 'country', $id: countryId } });

使用这个
oid=ObjectId()db.country.insert({u id:oid,代码:1,名称:'Brasil'});insert({code:1,state:'SC',country:{$ref:'country',$id:oid}})。你能把这个添加到你的答案中吗?@BetoNeto可以随意发布你自己的答案——你甚至可以自己接受它!这样,未来的访问者将可以在各种选项之间进行选择,并可以通过投票向上或向下表达他们的意见。
var countryId = Object();
db.country.insert({ _id: countryId, code: 1, name: 'Brasil' });
db.state.insert({ code: 1, name: 'SC', contry : { $ref: 'country', $id: countryId } });