Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to import json file to mongo

I've been trying to use mongo with some data imported, but I'm not able to use it properly with my document description.

This is an example of the .json I import using mongoimport: https://gist.github.com/2917854

mongoimport -d test -c example data.json 

I noticed that all my document it's imported to a unique object in spite of creating one of object for each shop.

That's why when I try to find a shop or anything I want to query, all the document is returned.

db.example.find({"shops.name":"x"}) 

I want to be able to query the db to obtain products by the id using dot notation something similar to:

db.example.find({"shops.name":"x","categories.type":"shirts","clothes.id":"1"} 

The problem is that all the document is imported like a single object. The question is: How
do I need to import the object to obtain my desired result?

like image 985
Nahikariii Avatar asked Jun 12 '12 14:06

Nahikariii


People also ask

How do I import a JSON file into MongoDB?

To import JSON file you need to follow the following steps: Step 1: Open a command prompt and give command mongod to connect with MongoDB server and don't close this cmd to stay connected to the server. Step 2: Open another command prompt and run the mongo shell. Using the mongo command.

How do I import files into MongoDB?

If you have CSV files (or TSV files - they're conceptually the same) to import, use the --type=csv or --type=tsv option to tell mongoimport what format to expect. Also important is to know whether your CSV file has a header row - where the first line doesn't contain data - instead it contains the name for each column.


1 Answers

Docs note that:

This utility takes a single file that contains 1 JSON/CSV/TSV string per line and inserts it.

In the structure you are using -assuming the errors on the gist are fixed- you are essentially importing one document with only shops field.

After breaking the data into separate shop docs, import using something like (shops being the collection name, makes more sense than using example):

mongoimport -d test -c shops data.json 

and then you can query like:

db.shops.find({"name":x,"categories.type":"shirts"}) 
like image 112
Eren Güven Avatar answered Sep 21 '22 03:09

Eren Güven