Question

I'm a beginner at MongoDB and I'm currently pairing it with php to try to make the following work:
I want to create a database to store information that can get updated at any time but it needs to keep a "document added on:" date.
In sum:

IF document exists:
-Update everything in the document except the "document added on" date entry.
ELSE
-Create a document with the data + a "document added on: XXXXX" date.

In a case of a database with this format:

Database{ document{ User_ID: "12345", Name: "Joe", More_Info: "" Date_Added_To_DB: "1372291496", Last_Updated:"1372291556"}}


I've researched and asked around and the best I've got so far is a function that will update a whole document if it exists and create a new document if it does not.

db.Database.update({'User_ID' : $userID},{$set: {'fieldName' : new "data" }}, {upsert: true})

Was it helpful?

Solution

The question is how you determine that "the document" exists? Usually, you'd do this using a unique id. Now MongoDB's ObjectId comes to the rescue because it contains a timestamp already. This can also be used in queries.

Instead of using an integer field User_ID, you might want to consider calling the field _id and use the ObjectId data type so you get that functionality for free.

> db.test.insert({"foo" : "test"});
{ "_id" : ObjectId("51cb763e58bb4077aea65b3d"), "foo" : "test" }
> var foo = db.test.findOne();
> foo._id.getTimestamp();
ISODate("2013-06-26T23:16:14Z")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top