user3313539
user3313539

Reputation: 133

Saving an ArrayList in MongoDB?

I want to switch to MongoDB for my database system. I have a Player class and I basically want to save that to the database. In the player class is a name, rank and a list of purchased items. What is the best way to store all this in MongoDB? I can create a document for the player but are you able to store a list in there? Thanks.

Upvotes: 0

Views: 3274

Answers (3)

Sasikanth
Sasikanth

Reputation: 3043

Yeah you can store arrays into mongodb first create a player document like this

db.player.insert({name:"xxx",rank:1});

you can insert the empty list at the time of creation like below or it will dynamically create when you update the document.

 db.player.insert({name:"xxx",rank:1,purchases:[]});//empty array optional

after creating the document you can update document with array like this

db.player.update({name:"xxx"},{$push:{purchases:["t-shirt","shoes"]});

It will create document like this:

{ "_id" : 1234,
  “name": “xxxx”,
  "rank": 1,
  “purchases”:
  [
           "t-shirt",
           "shoes"  
  ]
}

Upvotes: 0

pgregory
pgregory

Reputation: 2093

Sure you can store list, look at MongoDB embedded documents

Upvotes: 1

Rafa Paez
Rafa Paez

Reputation: 4870

Yes, you can use and store Arrays in MongoDB.

Check out this article. It will help you a lot: http://blog.mongolab.com/2013/04/thinking-about-arrays-in-mongodb/

Upvotes: 0

Related Questions