Proper way to import json file to mongo

前端 未结 4 835
半阙折子戏
半阙折子戏 2020-12-08 04:12

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 u

相关标签:
4条回答
  • 2020-12-08 04:35

    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"})
    
    0 讨论(0)
  • 2020-12-08 04:40

    There is a parameter --jsonArray:

    Accept import of data expressed with multiple MongoDB document within a single JSON array

    Using this option you can feed it an array, so you only need to strip the outer object syntax i.e. everything at the beginning until and including "shops" :, and the } at the end.

    Myself I use a little tool called jq that can extract the array from command line:

    ./jq '.shops' shops.json
    
    0 讨论(0)
  • 2020-12-08 04:47

    Importing a JSON

    The command mongoimport allows us to import human readable JSON in a specific database & a collection. To import a JSON data in a specific database & a collection, type mongoimport -d databaseName -c collectionName jsonFileName.json

    0 讨论(0)
  • 2020-12-08 04:56

    IMPORT FROM JSON

    mongoimport --db "databaseName" --collection "collectionName" --type json --file "fileName.json" --jsonArray
    

    JSON format should be in this format. (Array of Objects)

    [
        { name: "Name1", msg: "This is msg 1" },
        { name: "Name2", msg: "This is msg 2" },
        { name: "Name3", msg: "This is msg 3" }
    ]
    

    IMPORT FROM CSV

    mongoimport --db "databaseName" --collection "collectionName" --type csv --file "fileName.csv" --headerline
    

    More Info

    https://docs.mongodb.com/getting-started/shell/import-data/

    0 讨论(0)
提交回复
热议问题