How to make the time stamp difference for inserting and updating record in mongo? - mongodb

I need to create a time stamp in my mongodb collection. Am using C# in front end .My code is :
internal static void CreateStudent(string Id, string Name,string strUserId)
{
MongoServer server = MongoServer.Create(ConnectionString);
MongoDatabase mydb = server.GetDatabase("Database");
MongoCollection<BsonDocument> Student = mydb.GetCollection<BsonDocument>("Student");
BsonDocument colectionGenre = new BsonDocument {
{ "Code", Id }, //Id is Auto Generated in sql. Fetch from there using Output parameter and save it in one variable and pass that here
{ "Name", Name },
{ "Status","Y"},
{"stamps" , new BsonDocument {
{"Ins_date", DateTime.Now},
{"up_date",""},
{"createUsr", strUserId},
{"updUsr", ""},
{"Ins_Ip", GetIP()},
{"Upd_IP",""}}}
};
Student.Insert(colectionGenre);
}
internal static void UpdateStudent(string Id, string Name,string strUserId)
{
MongoServer server = MongoServer.Create(ConnectionString);
MongoDatabase mydb = server.GetDatabase("Database");
MongoCollection<BsonDocument>Student = mydb.GetCollection<BsonDocument>("Student"); ;
// Query for fetch the ID which is edited by the User...(user can only able to edit the NAME field alone)
var query = new QueryDocument {
{ "Code", Id }};
// After Fetch the correspondent ID it updates the name with the Edited one
var update = new UpdateDocument {
{ "$set", new BsonDocument("Name", Name) }
};
// Updated Query.(Id is same as previous. Name is updated with new one)
{"stamps" , new BsonDocument {
{"up_date",DateTime.Now},
{"updUsr", strUserId},
{"Upd_IP",GetIp()}}}
}}
};
Student.Update(query,update,UpdateFlags.Upsert, SafeMode.True);
}
It works fine for INSERT method with time(Stamp) once the record is created. But the problem is with update method. When user update something the insert time also changed with the updated time..
After User Updates the Name, i want my will collection looks like this
{
"_id" : ObjectId("5178aea4e6d8e401e8e51dc0"),
"Code": 12,
"Name": Sname,
"Stamps:"{
"Ins_date":03:34:00,
"up_date": 04:35:12
}
}
But my problem is both the time will same after update. That is because it takes the current date and time function..How can i achieve the above output.It needs any driver.Suggest something for me...

You're passing in a value for the Ins_date field when you're updating the document. Just remove that from the update document and it won't change it.
var update = new UpdateDocument {
{"$set", new BsonDocument {
{"State_strName", name},
{"stamps" , new BsonDocument {
{"up_date",DateTime.Now},
{"createUsr", ""},
{"updUsr", ""},
{"Ins_Ip", GetIP()},
{"Upd_IP",GetIP()}}}
};
tblmytbl.Update(query, update);

How you are updating the value in the existing document by using unique id or other unique value.Check whether the unique id or value is already exist in your database documents.If it is exist means change the update time only don't do anything..

While updating the data in mongoDB,you are passing the same values for Ins_date and up_date i.e. DateTime.Now(current system date and time).So the same values are updating in your monoDB document.
For this you can do one thing :-
Before updating your mongoDB document you take Ins_date values from your database by using sql query in C#.net and then use this value for Ins_date and for up_date use DateTime.Now then your both values will be different.
var update = new UpdateDocument {
{"$set", new BsonDocument {
{"State_strName", name},
{"stamps" , new BsonDocument {
{"Ins_date", **Ins_date values_from your database**} ,
{"up_date",DateTime.Now},
{"createUsr", ""},
{"updUsr", ""},
{"Ins_Ip", GetIP()},
{"Upd_IP",GetIP()}}}
};
tblmytbl.Update(query, update);

Sounds like what you need is the new $setOnInsert operator which was added in 2.4 for exactly this use case.
When the update with upsert flag results in an insert, you want to $set insert_date to Date.now but when it's a regular update, you don't want to set it at all. So now with your update you should use $set for regular fields you want to set whether it's an update or an insert, but use $setOnInsert for fields that should only be set during insert.

Finally I got answer...In INSERT method Simply pass the below things
{"Insert-stamps" , new BsonDocument {
{"Ins_date", DateTime.Now},
{"createUsr", strUserId},
{"Ins_Ip", GetIP()}}},
{"Update-stamps" , new BsonDocument {
{"up_date",""},
{"updUsr", ""},
{"Upd_IP",""}}}
And In UPDATE method
{"Update-stamps" , new BsonDocument {
{"up_date", DateTime.Now},
{"updUsr", StrUserId},
{"Upd_IP",GetIP()}}}
It works Fine for my standard....

Related

ObjectId as key to another collection-Migration

I am trying to add the ObjectId as a "Foreign key" to a collection. I have the previous id to link but I am having problem with the script.
Following is the script
db.users.find().forEach(function (user) {
var cursor = db.po1.find({"owner:": user.ID});
cursor.forEach(function(property) {
property.user_id = user._id;
db.po1.save(property);
});
});
The script runs but I do not get the field added to the documents of the po1 collection.
I am using mongoose for the api so I need the ObjectId. I do not want to embed the documents because of the rarity of the calls and the size of the po1 per user.
user.ID and po1.owner field are of the same type.
Thanks you for your time
From comment the answer.
Although save() has also been deprecated and finally the bellow script did the trick
db.users.find().forEach(function (user) {
var cursor = db.views.find({"user": user.ID});
cursor.forEach(function(object) {
object.userId = user._id;
db.views1.insertOne(object);
});
});
So through the innsert I created new collection and dropped previous.

FindAndModify: get newDocument along with info whether doc was inserted or updated

Using findAndModify:
I need to get the new resulting document
I need to know if an insert or update was done
var newUpdate = {
$set : newData,
$setOnInsert: {created_at: new Date()}
};
var options = {
upsert :true,
new: true,
};
collectionDriver.findAndModify(colName, query, newUpdate, options, function(err,resultDoc)
{
if (err) {
} else {
}
});
I get the new document, how can I know if an insert/update was happened?
One possible, though not the most efficient way, can be to check for presence of record before issuing the modify command because if you need the new record, then you cannot check if it previously existed.

Invoke db.eval in FindAndModify using MongoDB C# Client

I have the following Document:
{
"_id": 100,
"Version": 1,
"Data": "Hello"
}
I have a function which return a number from a sequence:
function getNextSequence(name) {
var ret = db.Counter.findAndModify(
{
query: { _id: name },
update: { $inc: { value: 1 } },
new: true,
upsert: true
}
);
return ret.value;
}
I can use this for optimistic concurrency by performing the following Mongo command:
db.CollectionName.findAndModify({
query: { "_id" : NumberLong(100), "Version" : 1 },
update: { "$set" : {
"Data": "Here is new data!",
"Version" : db.eval('getNextSequence("CollectionName")') }
},
new: true
}
);
This will update the document (as the _id and Version) match, with the new Data field, and also the new number out of the eval call.
It also returns a modified document, from which I can retrieve the new Version value if I want to make another update later (in the same 'session').
My problem is:
You cannot create an Update document using the MongoDB C# client that will serialize to this command.
I used:
var update = Update.Combine(
new UpdateDocument("$set", doc),
Update.Set(versionMap.ElementName, new BsonJavaScript("db.eval('getNextSequence(\"Version:CollectionName\")')")))
);
If you use what I first expected to perform this task, BsonJavascript, you get the following document, which incorrectly sets Version to a string of javascript.
update: { "$set" : {
"Data": "Here is new data!",
"Version" : { "$code" : "db.eval('getNextSequence(\"Version:CollectionName\")')" }
}
}
How can I get MongoDB C# client to serialize an Update document with my db.eval function call in it?
I have tried to add a new BsonValue type in my assembly which I would serialize down to db.eval(''); However there is a BsonType enum which I cannot modify, without making a mod to MongoDB which I would not like to do incase of any issues with the change, compatibility etc.
I have also tried simply creating the Update document myself as a BsonDocument, however FindAndModify will only accept an IMongoUpdate interface which a simply a marker that at present I find superfluous.
I have just tried to construct the command manually by creating a BsonDocument myself to set the Value: db.eval, however I get the following exception:
A String value cannot be written to the root level of a BSON document.
I see no other way now than drop down to the Mongo stream level to accomplish this.
So I gave up with trying to get Mongo C# Client to do what I needed and instead wrote the following MongoDB function to do this for me:
db.system.js.save(
{
_id : "optimisticFindAndModify" ,
value : function optimisticFindAndModify(collectionName, operationArgs) {
var collection = db.getCollection(collectionName);
var ret = collection.findAndModify(operationArgs);
return ret;
}
}
);
This will get the collection to operate over, and execute the passed operationArgs in a FindAndModify operation.
Because I could not get the shell to set a literal value (ie, not a "quoted string") on a javascript object, I had to to this in my C# code:
var counterName = "Version:" + CollectionName;
var sequenceJs = string.Format("getNextSequence(\"{0}\")", counterName);
var doc = entity.ToBsonDocument();
doc.Remove("_id");
doc.Remove(versionMap.ElementName);
doc.Add(versionMap.ElementName, "SEQUENCEJS");
var findAndModifyDocument = new BsonDocument
{
{"query", query.ToBsonDocument()},
{"update", doc},
{"new", true},
{"fields", Fields.Include(versionMap.ElementName).ToBsonDocument() }
};
// We have to strip the quotes from getNextSequence.
var findAndModifyArgs = findAndModifyDocument.ToString();
findAndModifyArgs = findAndModifyArgs.Replace("\"SEQUENCEJS\"", sequenceJs);
var evalCommand = string.Format("db.eval('optimisticFindAndModify(\"{0}\", {1})');", CollectionName, findAndModifyArgs);
var modifiedDocument = Database.Eval(new EvalArgs
{
Code = new BsonJavaScript(evalCommand)
});
The result of this is that I can now call my Sequence Javascript, the getNextSequence function, inside the optimisticFindAndModify function.
Unforunately I had to use a string replace in C# as again there is no way of setting a BsonDocument to use the literal type db.eval necessary, although Mongo Shell likes it just fine.
All is now working.
EDIT:
Although, if you really want to push boundaries, and are actually awake, you will realize this same action can be accomplished by performing an $inc on the Version field.... and none of this is necessary....
However: If you want to follow along to the MongoDB tutorial on how they to say to implement concurrency, or you just want to use a function in a FindAndModify, this will help you. I know I'll probably refer back to it a few times in this project!

inserting a new document in the arrray of documents

I want to add a new document to the following document having an outer key "User"
{
name:himani,
User:[
{
_id:e25ffgf627627,
Name:User1
},
{
_id:fri2i2jhjh9098,
Name:User2
}
]
};
Below is my code in which I am trying to add a new document to already existing document.
My code is:
var server = MongoServer.Create("mongodb://username:password#localhost:27017/?safe=true");
SafeMode mode = new SafeMode(true);
SafeModeResult result = new SafeModeResult();
var db = server.GetDatabase("himani");
var coll = db.GetCollection("test");
BsonDocument document = new BsonDocument();
document.Add("name", "himani");
result = coll.Insert(document, mode);
BsonDocument nested = new BsonDocument();
nested.Add("1", "heena").Add("2", "divya");
BsonArray a = new BsonArray();
a.Add(2);
a.Add(5);
nested.Add("values", a);
document["3"] = new BsonArray().Add(BsonValue.Create(nested));
coll.Save(document);
var query = Query.And(
Query.EQ("name", "himani"),
Query.EQ("3.1", "heena")
);
var match = coll.FindOne(query);
var update = Update.AddToSet("3", new BsonDocument {{ "count", "2" }});
coll.Update(query, update);
I want to add a new document to the User array. I am doing this by above code but its not working.Please tell me the right way of doing it.
I don't understand your document structure at all... and the only "user" array I could find in here was a field called "3". Your code does in fact work and appends a document into the "3" array. The below is the result after running your code. Perhaps you could be more clear as to what you want your document to look like after you have "appended" a user.
{
"_id":ObjectId("4fa7d965ce48f3216c52c6c7"),
"name":"himani",
"3":[
{
"1":"heena",
"2":"divya",
"values":[ 2, 5 ]
},
{
"count":"2"
}
]
}

Nested document insert into MongoDB with C#

I am trying to insert nested documents in to a MongoDB using C#. I have a collection called categories. In that collection there must exist documents with 2 array, one named categories and one named standards. Inside those arrays must exist new documents with their own ID's that also contain arrays of the same names listed above. Below is what I have so far but I am unsure how to proceed. If you look at the code what I want to do is add the "namingConventions" document nested under the categories array in the categories document however namingConventions must have a unique ID also.
At this point I am not sure I have done any of this the best way possible so I am open to any and all advice on this entire thing.
namespace ClassLibrary1
{
using MongoDB.Bson;
using MongoDB.Driver;
public class Class1
{
public void test()
{
string connectionString = "mongodb://localhost";
MongoServer server = MongoServer.Create(connectionString);
MongoDatabase standards = server.GetDatabase("Standards");
MongoCollection<BsonDocument> categories = standards.GetCollection<BsonDocument>("catagories");
BsonDocument[] batch = {
new BsonDocument { { "categories", new BsonArray {} },
{ "standards", new BsonArray { } } },
new BsonDocument { { "catagories", new BsonArray { } },
{ "standards", new BsonArray { } } },
};
categories.InsertBatch(batch);
((BsonArray)batch[0]["categories"]).Add(batch[1]);
categories.Save(batch[0]);
}
}
}
For clarity this is what I need:
What I am doing is building a coding standards site. The company wants all the standards stored in MongoDB in a tree. Everything must have a unique ID so that on top of being queried as a tree it can be queried by itself also. An example could be:
/* 0 */
{
"_id" : ObjectId("4fb39795b74861183c713807"),
"catagories" : [],
"standards" : []
}
/* 1 */
{
"_id" : ObjectId("4fb39795b74861183c713806"),
"categories" : [{
"_id" : ObjectId("4fb39795b74861183c713807"),
"catagories" : [],
"standards" : []
}],
"standards" : []
}
Now I have written code to make this happen but the issue seems to be that when I add object "0" to the categories array in object "1" it is not making a reference but instead copying it. This will not due because if changes are made they will be made to the original object "0" so they will not be pushed to the copy being made in the categories array, at least that is what is happening to me. I hope this clears up what I am looking for.
So, based on your latest comment, it seems as though this is the actual structure you are looking for:
{
_id: ObjectId(),
name: "NamingConventions",
categories: [
{
id: ObjectId(),
name: "Namespaces",
standards: [
{
id: ObjectId(),
name: "TitleCased",
description: "Namespaces must be Title Cased."
},
{
id: ObjectId().
name: "NoAbbreviations",
description: "Namespaces must not use abbreviations."
}
]
},
{
id: ObjectId(),
name: "Variables",
standards: [
{
id: ObjectId(),
name: "CamelCased",
description: "variables must be camel cased."
}
]
}
]
}
Assuming this is correct, then the below is how you would insert one of these:
var collection = db.GetCollection("some collection name");
var root = new BsonDocument();
root.Add("name", "NamingConventions");
var rootCategories = new BsonArray();
rootCategories.Add(new BsonDocument
{
{ "id": ObjectId.GenerateNewId() },
{ "name", "Namespaces" },
{ "standards", new BsonArray() }
});
root.Add("categories", rootCategories);
//etc...
collection.Save(root);
Hope that helps, if not, I give up :).
So, I guess I'm confused by what you are asking. If you just want to store the namingConventions documents inside the array, you don't need a collection for them. Instead, just add them to the bson array and store them.
var categoriesCollection = db.GetCollection<BsonDocument>("categories");
var category = new BsonDocument();
var namingConventions = new BsonArray();
namingConventions.Add(new BsonDocument("convention1", "value"));
category.Add("naming_conventions", namingConventions);
categoriesCollection.Insert(category);
This will create a new document for a category, create an array in it called naming_conventions with a single document in it with an element called "convention1" and a value of "value".
I also am not quite sure what you are trying to accomplish. Perhaps if you posted some sample documents in JSON format we could show you the C# code to write documents that match that.
Alternatively, if you wish to discuss your schema, that could also be better done in the context of JSON rather than C#, and once a schema has been settled on then we can discuss how to write documents to that schema in C#.
One thing that didn't sound right in your original description was the statement "in that collection must exist 2 arrays". A collection can only contain documents, not arrays. The documents themselves can contain arrays if you want.
var filter = Builders<CollectionDefination>.Filter.Where(r => r._id== id);
var data = Builders<CollectionDefination>.Update.Push(f=>
f.categories,categoriesObject);
await _dbService.collection.UpdateOneAsync( filter,data);
Note: Make sure embedded document type [Categories] is array.