Search code examples
mongodbmongoimport

How can I import records in MongoDb with relationship between collections?


I need to import data using a .json file, in the record I want to insert there is the relationship with Blog and Tag, to insert DBRef into the blog and tag fields I'm doing this way:

{"_id":null,"title":"462 Locust Avenue, Hamilton, Nevada, 7422","content":"Id sunt labore labore et nisi ad reprehenderit.","date":{"$date":{"$numberLong":"1577843940000"}},"blog": {"$ref":"blog", "$id": "5ce5539c07a6fa40b8b76651"},"tags":[{"$ref":"tag", "$id": "5ce594ba75a21c17dcc2d74e"}],"_class":"com.company.blog.domain.Entry"}

However, when querying the data, the data for blog and tag appear like this:

_id: ObjectId("5ce6e7bdf0888414e0d017f1")
title:"462 Locust Avenue, Hamilton, Nevada, 7422"
content:"Id sunt labore labore et nisi ad reprehenderit cupidatat aliqua. Ullam..."
date:2020-01-01T01:59:00.000+00:00
blog:DBRef(undefined, 5ce5539c07a6fa40b8b76651, undefined)
tags: Array
    0:DBRef(undefined, 5ce594ba75a21c17dcc2d74e, undefined)

In DBRef the first parameter should be the collection name instead of 'undefined', how can I change the .json to get the collection name after importing?


Solution

  • If your Json file isn’t too big, why don’t you rename the undefined text with the collection name and then import it.

    Or try this

    mongoimport --db testDB --collection Blog --file Blog.json