使用insertMany命令还原bson文档



我需要在mongodb中恢复许多带有许多文档的集合,但我只有其中的json文档,并且我没有使用bash执行mongorestore的权限。

如何仅使用mongo脚本(例如db.collection.insertMany(恢复json文档?

下面是一个从Mongo shell运行的示例。书籍数据是JSON,并存储为一个数组。有3本书的数据:

> var booksArr = [
{
"title" : "To Kill a Mockingbird",
"author" : "Harper Lee",
"goodreadsRating" : 4.3,
"published" : "1960-07-11T00:00:00Z",
"genres" : [
"Novel",
"Domestic Fiction",
"Legal Story"
]
},
{
"title" : "Hamlet",
"author" : "Willian Shakespeare",
"genres" : [
"Tragedy",
"Drama"
],
"goodreadsRating" : 4,
"published" : "1599-01-01T00:00:00Z"
},
{
"title" : "My Man Jeeves",
"author" : "P. G. Wodehouse",
"genres" : [
"Short story",
"Humorous Fiction"
],
"goodreadsRating" : 4.1,
"published" : "1919-05-01T00:00:00Z"
}
];

插入books2集合,并读取集合以查看插入的文档:

> db.books2.insertMany(booksArr);
> db.books2.findOne()
{
"_id" : ObjectId("5dc4dcc9c2ac920e04692774"),
"title" : "To Kill a Mockingbird",
"author" : "Harper Lee",
"goodreadsRating" : 4.3,
"published" : "1960-07-11T00:00:00Z",
"genres" : [
"Novel",
"Domestic Fiction",
"Legal Story"
]
}

请注意,_id字段和值是自动创建的。但是,您可以在JSON中提供自己的JSON,并且这些JSON对于集合中的每个文档都必须是唯一的。

请参阅published字段,它是以字符串形式存储的日期数据。MongoDB文档数据具有BSON类型的数据(它是JSON的扩展版本(。您可以稍后将字符串日期转换为Date字段(根据需要;另请参阅扩展JSON(。

最新更新