This question already has answers here:
MongoDB: Updating documents using data from the same document [duplicate]
(6 answers)
Closed 6 years ago.
const string Pattern = #"(?si)<([^\s<]*totalWork[^\s<]*)>.*?</\1>";
var filter = Builders<JobInfoRecord>.Filter.Regex(x => x.SerializedBackgroundJobInfo,
new BsonRegularExpression(Pattern, "i"));
var documents = await records.Find(filter).ToListAsync();
====
After I get documents I working with each document on the my side.
const string EmptyTag = "<$1></$1>";
var updatedJobInfo = Regex.Replace(document.SerializedBackgroundJobInfo, Pattern, EmptyTag);
How can I do Regex.Replace in the mongo side? Or that can only happen in the client?
Is the following Replace works in the Mongo side?
using (var cursor = await jobInfoDocuments.FindAsync<JobInfoRecord>(filter))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var document in batch)
{
var newInfo = Regex.Replace(document.SerializedBackgroundJobInfo, regex, EmptyTag);
// Applying several operations within the one request.
operationList.Add(new UpdateOneModel<JobInfoRecord>(Builders<JobInfoRecord>.Filter.Eq("_id", document.JobId),
Builders<JobInfoRecord>.Update.Set("SerializedBackgroundJobInfo", newInfo)));
}
You can do it with javascript but be sure the fix the filter to work with mongo shell
db.records.find(filter).forEach(function (doc) {
var pattern = /<([^\s<]*totalWork[^\s<]*)>[\s\S]*?</\1>/i;
var EmptyTag = "<$1></$1>";
doc.SerializedBackgroundJobInfo = doc.SerializedBackgroundJobInfo.replace(pattern, EmptyTag);
db.records.save(doc);
})
Related
I have 2 collections in my database. Let's say collection_1 and collection_2. I want to copy or move all of my documents in collection_1 to collection_2 using C#.
Any idea please?
Here's a solution to copy between databases. If they are on the same database then it is even more simple, just use one mongo client
var fromConnectionString = "mongodb://localhost:27017"; // if copy between same database then obviously you only need one connectionstring and one MongoClient
var toConnectionString = "mongodb://localhost:27017";
var sourceClient = new MongoClient(fromConnectionString);
var copyFromDb = sourceClient.GetDatabase("CopyFromDatabaseName");
var copyCollection = copyFromDb.GetCollection<BsonDocument>("FromCollectionName").AsQueryable(); // or use the c# class in the collection
var targetClient = new MongoClient(toConnectionString);
var targetMongoDb = targetClient.GetDatabase("CopyToDatabase");
var targetCollection = targetMongoDb.GetCollection<BsonDocument>("ToCollectionName");
targetCollection.InsertMany(copyCollection);
With database query.
Source :https://docs.mongodb.com/manual/reference/method/db.cloneCollection/
db.cloneCollection('mongodb.example.net:27017', 'profiles', { 'active' : true } )
With C#
Source: Duplicate a mongodb collection
var source = db.GetCollection("test");
var dest = db.GetCollection("testcopy");
dest.InsertBatch(source.FindAll());
i am trying to find documents in collection by ids. Most of the suggested answers use C# class that matches with the document. something like here
var filter = Builders<Product>.Filter
.In(p => p.Id, productObjectIDs);
i don't have corresponding C# class, so i am using BsonDocument
public async Task<IEnumerable<BsonDocument>> GetData(IEnumerable<int> documentIds)
{
var collection = _mongoDatabase.GetCollection<BsonDocument>("mycollection");
// how do set filter here
var filterBuilder = Builders<BsonDocument>.Filter.In<int>("???????", documentIds);
var projection = Builders<BsonDocument>.Projection
.Include("_id")
.Include("status")
.Include("units");
var result = await collection.Find(filterBuilder).Project<BsonDocument>(projection).ToListAsync().ConfigureAwait(false);
return result;
}
I am not sure how do i set filter with in operator?
You may try this filter:
var filter = new BsonDocument("_id", new BsonDocument("$in", new BsonArray(documetIds)));
Based on this answer
Using CosmoDb with MongoDb api from c# I can update a document with filter condition rather than using the Id.
For example this code work fine with CosmoDb with MongoDb api.
public bool UpdateTask(MyTask myTask)
{
var mongoCollection = GetBsonCollectionForEdit();
var builder = Builders<BsonDocument>.Filter;
var filterName = builder.Eq("Name", myTask.Name);
var filterCategory = builder.Eq("Category", myTask.Category);
var filter = builder.And(new[] { filterName, filterCategory });
var replaceUpdate = Builders<BsonDocument>.Update;
var ret = mongoCollection.ReplaceOne(filter, myTask.ToBsonDocument());
return ret.ModifiedCount == 1;
}
Can I do the same thing with CosmoDb using the SQL DocumentDb api ?
(Without implement UDF or StoredPoc)
Thanks
No, but you can perform a query for the criteria using CreateDocumentQuery, then iterate through the matching IDs and perform an update on each of them using ReplaceDocumentAsync.
This question already has answers here:
How to Convert JSON object to Custom C# object?
(13 answers)
Closed 5 years ago.
i want to get the data from my returning api jsonstring.
my result string looks like this
[
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
{"Id":12,"name":"testname","type":"testtype"}
]
how can i extract this data to c# objects
i can only do it ones
var obj = JObject.Parse(result);
var ID = (int)obj["Id"];
var Name = (String)obj["name"];
var type = (String)obj["type"];
User u = new User(ID,Name,Type);
Your string is not valid JSON, so making it valid JSON is the first step to process it quickly. The easiest thing to do is to make it a JSON array:
string jsonArray = "["
+ string.Join(", ", json.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
+ "]";
From then on it is straightforward (see my related answer: Easiest way to parse JSON response):
var result = JsonConvert.DeserializeObject<User[]>(jsonArray);
Another option is to split the lines yourself, and parse and add the items to a list manually.
Result is an array of JSON.. so loop and parse
list<User> userList = new list<User>();
for(int i=0 ; i <result.length; i++)
{
var obj = JObject.Parse(result[i]);
var ID = (int)obj["Id"];
var Name = (String)obj["name"];
var type = (String)obj["type"];
User u = new User(ID,Name,Type); //create User
userList.add(u); //Add to list
}
This question already has answers here:
Read the content of the string intern pool
(2 answers)
Closed 7 years ago.
Is there any way I can see the contents of the string table in a running .NET application?
I want to compare a console application with vanilla string concatinations and one using the string builder.
You can use ClrMD to attach to a process and retrieve information from it. Something along the lines of the following should work:
var proc = Process.GetProcessesByName("myapp.exe").FirstOrDefault();
using (var target = DataTarget.AttachToProcess(proc.Id, 1000))
{
var runtime = target.ClrVersions[0].CreateRuntime();
var heap = runtime.GetHeap();
foreach (var obj in heap.EnumerateObjectAddresses())
{
var type = heap.GetObjectType(obj);
if (type.Name == "System.String")
{
var value = (string)type.GetValue(obj);
// Write value to disk or something.
}
}
}