1

I have a bunch of JSON files (say a.json, b.json, c.json). I know I can import each of them into a MongoDB collection using

mongoimport -d db -c collection --file x.json --jsonArray

And my collection will contain the three jsons. But I'd like to have the jsons be the values to keys which identify them. That is, instead of having my collection contain the following:

a.json, b.json, c.json

I'd like:

{ "a" : a.json }, { "b" : b.json }, { "c" : c.json }

Is there some functionality in Mongo's insert() method like: db.collection.insert( { "a" : a.json } ) ?

1 Answer 1

1

You can use jq JSON parser to merge your 3 files with the required format and then import it with mongoimport :

jq -s '{"a":.[0],"b":.[1],"c":.[2] }' a.json b.json c.json

Btw, it will work even if your json files have different root element (json object or array). The result will be like :

{
  "a": [
    {
      "field": "2"
    },
    {
      "field": "5"
    }
  ],
  "b": [
    {
      "field": "2"
    },
    {
      "field": "1"
    }
  ],
  "c": [
    {
      "field": "3"
    },
    {
      "field": "2"
    }
  ]
}

You can store this into a new json file and then import it into mongoDB :

jq -s '{"a":.[0],"b":.[1],"c":.[2] }' a.json b.json c.json > input.json

mongoimport -d db -c testDB --file input.json

The result would be :

{ "_id" : ObjectId("58b2fa56fa97671e9876afa8"), "a" : [ { "field" : "2" }, { "field" : "5" } ], "b" : [ { "field" : "2" }, { "field" : "1" } ], "c" : [ { "field" : "3" }, { "field" : "2" } ] }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.