Inserting document to MongoDB from mongodump JSON with pymongo - json

I have a JSON file (converted from mongodump BSON) which I would like to insert to a MongoDB using pymongo.
The approach I am using is something like:
with open('duplicate_docs.json') as f:
lines = f.readlines()
for line in lines:
record = json.loads(line)
db.insert_one(record)
However, the JSON is in the form:
{ "_id" : ObjectId( "54ccc3f469702d45ca450200"), \"id\":\"54713efd69702d78d1420500\",\"name\":\"response"}
As you can see there are escape charaters () for the JSON keys and I am not able to load this as a JSON.
What is the best way yo fix a JSON string like this so it can be used to do insert to MongoDB?
Thank you.

As an alternative approach if you take the actual output of mongodump you can insert it straight in with the bson.json_util loads() function.
from pymongo import MongoClient
from bson.json_util import loads
db = MongoClient()['mydatabase']
with open('c:/temp/duplicate_docs.json', mode='w') as f:
f.write('{"_id":{"$oid":"54ccc3f469702d45ca450200"},"id":"54713efd69702d78d1420500","name":"response"}')
with open('c:/temp/duplicate_docs.json') as f:
lines = f.readlines()
for line in lines:
record = loads(line)
db.docs.insert_one(record)

why not use mongoexport to dump to json not bson
mongoexport --port 27017 --db <database> --collection <collection> --out output.json
and then use
mongoimport --port 27017 --db <database> --collection <collection> --file output.json

Related

Is there way to mongoimport data with json inside json?

I have to migrate data from PostgreSQL to MongoDB.
In psql this table looks like:
id | json_token
(1000001,300) | { "type": "service_account", "project_id": "euzone-testbed-app", "private_key_id": "7f86abe060fd2e80fcbdd8118769483f332d9345" }
(1 row)
First step: get json file from psql table
sudo -u postgres psql -d component_name -c "\copy (SELECT replace(replace(replace(json_agg(sub)::text, E'\n', ''), 'account_id', 'accountId'), 'id', '_id') FROM (select foo.id, foo.json_token from foo_table foo) sub) to '/tmp/foo.json'"
In out of this command I have file:
[{"_id":{"accountId":1000001,"_id":300},"json_token":"{ \\"type\\": \\"service_account\\", \\"project__id\\": \\"euzone-testbed-app\\", \\"private_key__id\\": \\"7f86abe060fd2e80fcbdd8118769483f332d9345\\" }"}]
and I have to import that in mongodb.
Problem next: I have json inside key "json_token" and seems, like mongoimport can't parse it.
[stormrage#dev tmp]$ mongoimport --db=db-name --collection=foo_collection --jsonArray --file=foo.json
2022-11-22T21:14:47.142+0300 connected to: localhost
2022-11-22T21:14:47.143+0300 Failed: error processing document #1: invalid character 't' after object key:value pair
2022-11-22T21:14:47.143+0300 imported 0 documents
Is there way to do it through mongoimport and avoid problem with json inside json?

json file items inserted as single item in mongodb

This is my first time using mongodb and I have a products.json file in the format of
{"products":[ {} , {} , {} ] }
and when I inserted it to mongodb with the command :
mongoimport --db databaseName --collection collectioname --file products.json
I got in my collection the products.json as a single document with a single object id not a doc with an id for every {} object in my array .Obviously my json format is incorrect and I would really appreciate your help with this since I am a beginner.
From what you described , what you need is to import with --collection products , and have your products in the json file to be as follow:
{}
{}
{}
Or you can modify the file content as follow:
[{},{},{}]
and add --jsonArray to the mongoimport command to load the array objects as separate documents ...

mongodb import csv to json with subobjects

I have file.csv with similar to this structure
loremipsum; machine, metal
As i understand, succeful import will looks like
{
text: "loremipsum", << string
tags: ["machine","metal"] << object with two fields
}
The best result i get
{
text: "loremipsum", << string
tags: "machine, metal" << string
}
If i understand it correctly then please tell me how to do succeful import. Thanks.
Edit: because "tags" object should contain ~16 urls, so tell me how it should be stored correctly.
Ideally, below command should be used to import csv file to mongoDb (Maybe you are using the same):
mongoimport --db users --type csv --headerline --file /filePath/fileName.csv
I think ,Your Problem is with array type of data (if I understood correctly...!!).
Then, You need to first add one document in collection and export it as CSV file. This will give you the format which is expected by above command to import your data correctly. And then Arrange your data as per exported CSV file.
link Answer Here Explained it Very well
I had this data in Excel
I wanted like this in MongoDB
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
I did replaced the headings like cars.0 cars.1 cars.2
Like this
I used the tool mongoimport and ran this command
mongoimport.exe --uri "mongodb+srv:/localhost/<MYDBName>" --username dbuser --collection ----drop --type csv --useArrayIndexFields --headerline --file 1.csv
here my csv is 1.csv

Removing the index of a collection in mongoDB?

I want to remove the id of my document in MongoDB.
I will put the document below:
{
"_id" : ObjectId("54f2324671eb13650e8b4569"),
"nome" : "Pr.Ademar Lourenço",
"tweet" : "Jornal Águas Lindas: Prefeito Hildo se reúne com governador Rollemberg e prefeitos do Entorno http://t.co/PtVWIENdO4"
}
I want you to be like this:
{
"nome" : "Pr.Ademar Lourenço",
"tweet" : "Jornal Águas Lindas: Prefeito Hildo se reúne com governador Rollemberg e prefeitos do Entorno http://t.co/PtVWIENdO4"
}
The reason and I'll export this document to a .txt and treats it out of MongoDB.
You can use mongoexport to export data in either json or csv format. There is a --fields option to this utility that will let you define which specific fields to export
--fields nome,tweet
Adjusting the examples in the reference documentation: http://docs.mongodb.org/v2.2/reference/mongoexport/ to your example.
For JSON
mongoexport --db sales --collection contacts --fields nome,tweet --out contacts.json
For CSV
mongoexport --db users --collection contacts --fields nome,tweet --csv --out contacts.csv
Hopefully this gives you enough to export your data into the form you want.
you can make a query and remove the _id field in projection parameter, example:
db.tweets.find({}, {_id:0});
this will remove the column _id in response.

Dump Mongo Collection into JSON format

Is there any way to dump mongo collection into json format? Either on the shell or using java driver.I am looking for the one with best performance.
Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.
mongoexport -d <database> -c <collection_name>
Also helpful:
-o: write the output to file, otherwise standard output is used (docs)
--jsonArray: generates a valid json document, instead of one json object per line (docs)
--pretty: outputs formatted json (docs)
Use mongoexport/mongoimport to dump/restore a collection:
Export JSON File:
mongoexport --db <database-name> --collection <collection-name> --out output.json
Import JSON File:
mongoimport --db <database-name> --collection <collection-name> --file input.json
WARNING
mongoimport and mongoexport do not reliably preserve all rich BSON data types because JSON can only represent a subset of the types supported by BSON. As a result, data exported or imported with these tools may lose some measure of fidelity.
Also, http://bsonspec.org/
BSON is designed to be fast to encode and decode. For example,
integers are stored as 32 (or 64) bit integers, so they don't need to
be parsed to and from text. This uses more space than JSON for small
integers, but is much faster to parse.
In addition to compactness, BSON adds additional data types
unavailable in JSON, notably the BinData and Date data types.
Here's mine command for reference:
mongoexport --db AppDB --collection files --pretty --out output.json
On Windows 7 (MongoDB 3.4), one has to move the cmd to the place where mongod.exe and mongo.exe file resides =>
C:\MongoDB\Server\3.4\bin else it won't work saying it does not recongnize mongoexport command.
From the Mongo documentation:
The mongoexport utility takes a collection and exports to either JSON or CSV. You can specify a filter for the query, or a list of fields to output
Read more here: http://www.mongodb.org/display/DOCS/mongoexport
Here is a little node script that I write to dump all collections in a specific database to the specified output directory...
#!/usr/bin/env node
import { MongoClient } from 'mongodb';
import { spawn } from 'child_process';
import fs from 'fs';
const DB_URI = 'mongodb://0.0.0.0:27017';
const DB_NAME = 'database-name';
const OUTPUT_DIR = 'output-directory';
const client = new MongoClient(DB_URI);
async function run() {
try {
await client.connect();
const db = client.db(DB_NAME);
const collections = await db.collections();
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR);
}
collections.forEach(async (c) => {
const name = c.collectionName;
await spawn('mongoexport', [
'--db',
DB_NAME,
'--collection',
name,
'--jsonArray',
'--pretty',
`--out=./${OUTPUT_DIR}/${name}.json`,
]);
});
} finally {
await client.close();
console.log(`DB Data for ${DB_NAME} has been written to ./${OUTPUT_DIR}/`);
}
}
run().catch(console.dir);