如何将 json 文件内容作为文档导入到 mongodb?
How to import json file content to mongodb as documents?
Users.json 文件:
{
"id": 1,
"name": "abc"
},
{
"id": 2,
"name": "pqr"
}
如何在 mongodb 中插入包含 50k 文档的 json 数据(作为文档而非数组)
您可以复制整个 json 然后使用 insert() 在相应的集合中插入一个文档。
例如:集合名称:users
db.getCollection('users').insert(
{
"Users": [{
"id": 1,
"name": "abc"
},
{
"id": 2,
"name": "pqr"
)]
})
为了添加多个文档然后使用 insertMany()
例如:
db.getCollection('users').insertMany(
[{
"Users": [{
"id": 1,
"name": "abc"
},
{
"id": 2,
"name": "pqr"
)]
},
{
"Users": [{
"id": 3,
"name": "abc"
},
{
"id": 4,
"name": "pqr"
)]
}]
)
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
您可以使用 mongo-shell mongo 使用下面给出的命令导入
mongoimport --db databaseName --collection collectionName --drop --file ~/path/to/file/fileName.json
Users.json 文件:
{
"id": 1,
"name": "abc"
},
{
"id": 2,
"name": "pqr"
}
如何在 mongodb 中插入包含 50k 文档的 json 数据(作为文档而非数组)
您可以复制整个 json 然后使用 insert() 在相应的集合中插入一个文档。
例如:集合名称:users
db.getCollection('users').insert(
{
"Users": [{
"id": 1,
"name": "abc"
},
{
"id": 2,
"name": "pqr"
)]
})
为了添加多个文档然后使用 insertMany()
例如:
db.getCollection('users').insertMany(
[{
"Users": [{
"id": 1,
"name": "abc"
},
{
"id": 2,
"name": "pqr"
)]
},
{
"Users": [{
"id": 3,
"name": "abc"
},
{
"id": 4,
"name": "pqr"
)]
}]
)
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
您可以使用 mongo-shell mongo 使用下面给出的命令导入
mongoimport --db databaseName --collection collectionName --drop --file ~/path/to/file/fileName.json