制作一个脚本来从 Mongo shell 创建 MongoDB 集合? [英] Make a script to create MongoDB collections from Mongo shell?

查看:81
本文介绍了制作一个脚本来从 Mongo shell 创建 MongoDB 集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮我写一下 Mongo Shell 脚本来为它创建新的集合和索引吗?这是我编写的代码的一部分,我需要重构它.

Could you please help me out in writing Mongo Shell script to create new collections and indexes to it. Here are some part of the code which i wrote and i need to refactored it.

db.createCollection("Dog", { autoIndexId : true});

db.createCollection("Cat", { autoIndexId : true});

db.createCollection("Mouse", { autoIndexId : true});

db.createCollection("Name", { autoIndexId : true});

在上面的代码中,我可以编写单个语句来创建多个集合吗?并一次性将多个索引添加到一个集合中?

In above code can i write single statement to create multiple collections? and also add multiple indexes to one collection in one go?

推荐答案

创建一个名为my_scripts.js"的文件,使用以下命令.这个 JavaScript 定义了数据和命令来创建两个集合(dogscats),它们的数据(JSON 文档)和索引(索引是在 集合的名称字段).

Create a file called as "my_scripts.js", with the following commands. This JavaScript defines the data and commands to create two collections (dogs and cats), their data (documents as JSON) and the indexes (indexes are created on the name field of the collection).

my_scripts.js:

let dogDocs = [
  {
    name: "pooch",
    breed: "poodle",
    weight: "6 lbs"
  },
  {
    name: "mutt",
    breed: "bulldog",
    weight: "10 lbs"
  }
];

let catDocs = [
  {
    name: "minni", 
    breed: "persian",
    color: "white"
  },
  {
    name: "tinkle",
    breed: "bombay",
    color: "black"
  }
];

let dogIndex = { name : 1 };
let catIndex = { name : 1 };

let collInfoObjs = [ 
  { coll: "dogs", data: dogDocs, index: dogIndex }, 
  { coll: "cats", data: catDocs, index: catIndex } 
];

for (obj of collInfoObjs) {
    db[obj.coll].insertMany(obj.data);
    db[obj.coll].createIndex(obj.index);
}


运行脚本文件:

mongo shell 运行脚本(您可以使用 load 命令指定文件路径):

From the mongo shell run the script as (you can specify the file path with the load command):

mongo > load("my_script.js");

脚本运行后,您可以单独使用以下命令来验证集合、它们的文档和索引:

After the script is run, you can use the following commands individually to verify the collections, their documents and the indexes:

db.dogs.find();
db.cats.find();
db.dogs.getIndexes();
db.cats.getIndexes();

请注意,如果您不在文档中提供 _id,文档将创建一个唯一的 _id 字段(ObjectId 类型).输入 JSON 数据.

Note that the documents will have a unique _id field (of type ObjectId) created if you don't supply the _id in the input JSON data.

这篇关于制作一个脚本来从 Mongo shell 创建 MongoDB 集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆