Reputation: 133
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
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
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