开发者

Is there a natural way to map a hash or a XML file to a Mongo document?

Is there a way to take a hash of data (or even better an XML开发者_StackOverflow社区 document) could be mapped straight to a mongo document. So this hash:

@hash = {
   "doc_id"       => 3928,
   "header"       =>[
       {"merchantId"=>["35701"], 
        "merchantName" =>["Lingerie.com"], 
        "createdOn"    =>["2011-09-23/00:33:35"]}
    ], 
   "trailer"      =>[
       {"numberOfProducts"=>["0"]}
    ]
}

Would become:

> db.doc.first()
{
  _id : ObjectId("4e77bb3b8a3e000000004f7a"),
  doc_id : 3928
  header : [{
      merchantId : "35701", 
      merchantName : Lingerie.com 
  }],
  trailer : [{
    numberOfProducts : 0 
  }]
}


You could convert the hash to json with to_json:

require 'json'

@hash.to_json

gets you(with formatting):

{
  "doc_id":3928,
  "header":[{
    "merchantId":["35701"],
    "merchantName":["Lingerie.com"],
    "createdOn":["2011-09-23/00:33:35"]
  }],
  "trailer":[{
    "numberOfProducts":["0"]
  }]
}

It should be just a short hop to bson and mongo from there.

Edit:

Okay, I just read the tutorial here: http://api.mongodb.org/ruby/current/file.TUTORIAL.html

and it looks like you can just put the hash in there and the mongodb driver takes care of it. Maybe I don't understand the question?


It's not clear what you're trying to do, so I'm assuming you want to import XML data into mongo.

I've been importing XML files to mongo. First I convert the xml files to json objects using this command line tool I wrote, xml-to-json. Then, I use mongoimport to import the data into mongo.

Check out the documentation of xml-to-json, including some example input vs. output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜