Quick links
| Ubuntu 22.04 | Mongo import | Mongo export
Prepare a mongo server instance:
1
2
3
|
docker run --rm --name mongo -d mongo:6
docker exec -it -w /root mongo bash
apt update && apt -y install curl less jq
|
We are in the container, so all command will run from root!
Import
MongoDB is one of the most popular NoSQL database engines. For our test we can take the most popularsample MongoDB database about restaurants:
1
2
|
curl -LO https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/primer-dataset.json
head primer-dataset.json | jq '.'
|
Let’s import it into database mydb and collection restaurants using mongoimport. Mongo will create :
1
2
3
|
mongoimport --db mydb --collection restaurants --file primer-dataset.json
2023-05-14T13:19:13.396+0000 connected to: mongodb://localhost/
2023-05-14T13:19:14.537+0000 25359 document(s) imported successfully. 0 document(s) failed to import.
|
Connect to out mydb:
Count the documents in collection restaurants and check a document in restaurants:
1
2
3
4
5
6
7
8
9
|
db.restaurants.countDocuments()
25359
db.restaurants.findOne()
{
_id: ObjectId("6460dfd11e50c976dc94fa60"),
address: {
building: '1007',
...
exit
|
Export
We should use mongoexport to export the restaurants collection from the mydb database which we have previously imported
1
|
mongoexport --db mydb -c restaurants --out mydbexport.json
|
If you need to get a part of our collection. For example, let’s find all the restaurants which satisfy the criteria to be situated in the Bronx borough and to have Italian cuisine:
1
2
3
4
5
6
|
mongosh mydb
db.restaurants.find( { "borough": "Bronx", "cuisine": "Italian" } )
exit
mongoexport --db mydb -c restaurants -q "{\"borough\": \"Bronx\", \"cuisine\": \"Italian\"}" --out Bronx_Italian_restaurants.json
less Bronx_Italian_restaurants.json
cat Bronx_Italian_restaurants.json | jq '.'
|
Usefull link here