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());
Related
I have two hashsets that I want to except to get the distinct data:
var dataA = new HashSet<string>();
var dataB = new HashSet<string>();
var exceptA = dataA.Except(dataB);
var exceptB = dataB.Except(dataA);
var result = exceptA.Union(exceptB);
var container = new HashSet<string>(result);
dgv_B.DataSource = container.ToList();
My problem is when I insert the container into the datageid, this is my result:
And this is the raw data from breakpoints:
How can I display the text in the DGV?
The answer was given by fellow #GoodNightNerdPride:
It seems that the DGV does not work with lists of primitive types. It expects objects and analyzes their properties to generate the columns (a string has a Length property). Try something like this instead:
dgv_B.DataSource = container.Select(s => new { Value = s }).ToList();
I'm developing a project using CosmosDb and Microsoft Azure Document library with c#.
I want to execute a stored procedure that retrieve all the record of a contsiner but the code retrieve only 100 record.
The code is the following :
string collectionToUse;
string partition;
if (typeof(T).ToString().IndexOf("Telemetry") != -1)
{
DocumentDBRepository<EBB.Web.Telemerty.Models.Telemetry>.Initialize();
collectionToUse = AppSettings.collection;
partition = "id";
}
else
{
DocumentDBRepository<EBB.Web.Telemerty.Models.Events>.Initialize();
collectionToUse = AppSettings.collection2;
partition = "uid";
}
Uri uri =
UriFactory.CreateStoredProcedureUri(AppSettings.database, collectionToUse, AppSettings.spName);
RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey(partition) };
var result = await client.ExecuteStoredProcedureAsync<string>(uri, options, null);
List<T> list = new List<T>();
list = JsonConvert.DeserializeObject<List<T>>(result.Response);
return list;
What is the problem?
Thanks in advance for help me.
Simone
In Cosmos DB stored procedures cannot return all the documents in the container because the scope of the stored procedure execution isn't the full container but rather ONLY the logical partition that you specify in the RequestOptions. This means that your SP will only return documents that have this logical partition value in their properties.
I'm trying to port over JavaScript code that interacts with a MongoDb to C# .NET and having problems with a delete/pull operation. I can't seem to figure out how to iterate over the Ponies array and remove a single ObjectId by matching to a passed in ObjectId.
{
"_id" : ObjectId("388e8a66fe2af4e35c60e"),
"Location" : "rainbowland",
"Ponies" : [
ObjectId("388e8a66fe2af4e35c24e83c"),
ObjectId("388e8a66fe2af4e35c24e860"),
ObjectId("388e8a66fe2af4e35c24e83d")
]
}
I've tried several different ways based on what I've found online but nothing seems to work. When I check the collection to see if 388e8a66fe2af4e35c24e860 was removed from the Ponies array I see that it wasn't removed. Everytime I execute the code and look at the ModifiedCount for resultPonies it shows zero. Two examples of what I've tried doing are below.
var pony = new Pony() { Id = new ObjectId("388e8a66fe2af4e35c24e860") }
var pullPonies = Builders<Ranch>.Update.PullFilter(x => x.Ponies,
y => y.Id == pony.Id);
var filterPonies = Builders<Ranch>.Filter.Where(x => true);
var resultPonies = _context.Ranches.UpdateMany(filterPonies, pullPonies);
OR
var pullPonies = Builders<BsonDocument>.Update.PullFilter("Ponies",
Builders<ObjectId>.Filter.Eq("ObjectId", pony.Id));
var filterPonies = Builders<BsonDocument>.Filter.Where(x => true);
var resultPonies = _context.Ranches.UpdateMany(filterPonies, pullPonies);
Here is the JavaScript code that I believe works but haven't been able to test yet.
db.collection("Ranches").update({}, {$pull: {Ponies: pony._id}}, {multi: true});
Ok, I found a solution for the problem. Since I'm not actually going to be filtering within the array of objects, they are all ObjectIds in a BsonArray, I need to find where the value in the array matches the given ObjectId. In those cases the array item should be pulled out. If the object in the array had other properties then I would probably want to use the PullFilter. But in this case I don't need to filter the additional level. That is at least what I believe I was doing wrong. Here are the solutions
var ponyId = new ObjectId("388e8a66fe2af4e35c24e860");
var pullPonies = Builders<Ranch>.Update.Pull(x => x.Ponies, ponyId);
// This line is to retrieve all Ranch objects in the collection
var filterPonies = Builders<Ranch>.Filter.Where(x => true);
var resultPonies = _context.Ranches.UpdateMany(filterPonies, pullPonies);
Or
var ponyId = new ObjectId("388e8a66fe2af4e35c24e860");
var pullPonies = Builders<BsonDocument>.Update.Pull("Ponies", ponyId));
// This line is to retrieve all Ranch objects in the collection
var filterPonies = Builders<BsonDocument>.Filter.Where(x => true);
var resultPonies = _context.Ranches.UpdateMany(filterPonies, pullPonies);
I need to read certain fields in documents from Mongo. I filtered out a document using the Filter.EQ() method but how can I find and store a field in that document? This is my code:
public void human_radioButton_Checked(object sender, RoutedEventArgs e)
{
Upload human = new Upload(); //opens connection to the database and collection
var filter = Builders<BsonDocument>.Filter.Eq("name", "Human");
race_desc description = new race_desc();
description.desc = Convert.ToString(filter);
desc_textBox.Text = description.desc;
However, this doesn't work since I didn't grab any fields, just the document. So how can I read a field called 'A' and store it into an object?
Thanks
When you define a filter using the Builders<BsonDocument>.Filter here, you merely define a filter that you can use/execute in a query. Much like storing a SQL string in a string variable.
What you missed here is executing the filter and actually retrieve the data. According to Mongodb C# driver doc:
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("borough", "Manhattan");
var result = await collection.Find(filter).ToListAsync();
Then you can iterate the results and access the properties like
foreach(var result in results)
{
//do something here with result.your_property
}
And if you just want the first of the result
var result = (await collection.Find(filter).ToListAsync()).FirstOrDefault();
Now if you want to cast the BsonDocument you got now to your own class deserialize document using BsonSerializer:
var myObj = BsonSerializer.Deserialize<YourType>(result);
You can also map it to your own class:
var yourClass = new YourType();
yourClass.Stuff= result["Stuff"].ToString();
var filter = new BsonDocument("filename", filename);
var list = await col.Find(filter).ToListAsync();
here are my code, I can't figure out what's the proper syntax to perform the task I wanted to do.
Not sure what you mean. I guess you want the returned document contains no _id field. To do so, you need a projection.
Try
var projection = new BsonDocument("_id", false);
var list = col.Find(filter).SetFields(new FieldsBuilder<YourClass>()
.Exclude(p => p.Id));
reference