我想用脚本初始化一个mongoDB因为我有一些我需要在开头有值的集合所以我按照说明操作:http://michelebusta.com/the-little-things-5-initialize-a-local-mongo-db/
我创建了一个(.js)文件,我加载它并且它可以工作,
class TeamSerializer(serializers.ModelSerializer):
class Meta:
model = Team
fields = ('id', 'name', 'members','services_used')
问题是我有这样的ID:" _id" :ObjectId(" 572b8601e6352994d76bb13e"), 我希望有一个自动增量ID(_id:1),请你帮帮我。
db.serviceSpeedList.insert({
_id: 0,
name:"DHL", service:"DHL Ground"});
db.serviceSpeedList.insert({
_id: 1,
name:"DHL", service:"DHL Second Day Service"});
db.serviceSpeedList.insert({
_id: 2,
name:"DHL", service:"DHL Express"});
db.serviceSpeedList.insert({
_id: 3,
name:"DHL", service:"DHL International Express"});
我用过
{
"_id" : ObjectId("572b8601e6352994d76bb139"),
"name" : "DHL",
"service" : "DHL Ground"
}
{
"_id" : ObjectId("572b8601e6352994d76bb13a"),
"name" : "DHL",
"service" : "DHL Second Day Service"
}
当我在shell中单独使用它时,它可以工作,但当我把它放在一个脚本中并使用load(" D:\ initMongo.js");它不起作用:(请帮帮我
答案 0 :(得分:1)
您可以将_id设置为任何其他属性,如果您有js文件,请考虑使用var i = 0;
并在每个插入语句中增加该值。
db.serviceSpeedList.insert({ "_id" : i++, name:"DHL", service:"DHL Ground"});
db.serviceSpeedList.insert({"_id" : i++, name:"DHL", service:"DHL Second Day Service"});
按照流程
> var i = 0;
> db.serviceSpeedList.insert({ "_id" : i++, name:"DHL", service:"DHL Ground"});
WriteResult({ "nInserted" : 1 })
> db.serviceSpeedList.findOne()
{ "_id" : 0, "name" : "DHL", "service" : "DHL Ground" }
> db.serviceSpeedList.insert({"_id" : i++, name:"DHL", service:"DHL Second Day S
ervice"});
WriteResult({ "nInserted" : 1 })
> db.serviceSpeedList.find()
{ "_id" : 0, "name" : "DHL", "service" : "DHL Ground" }
{ "_id" : 1, "name" : "DHL", "service" : "DHL Second Day Service" }
>
答案 1 :(得分:1)
您必须在mongodb数据库中执行自动增量序列才能执行此操作。可以找到完整的例子:https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/