Reputation: 4009
I have an application that is using Mongo DB currently. I am looking to move the app to Azure and trying to use Cosmos DB. I upgraded the C# Mongo DB Driver in the code to the latest version 2.7.0 and it is working all fine still using Mongo DB.
I then used the Cosmos DB Migration Tool to migrate Data to the Azure Cosmos DB Emulator and changed the connection string in my web config to point to the emulator. The Application is loading and some reference data is getting returned on my first screen but my GetById query below is not working?
public virtual T GetById(TKey id)
{
if (typeof(T).IsSubclassOf(typeof(EntityBase)))
{
return GetById(new ObjectId(id as string));
}
//code removed for brevity
}
public virtual T GetById(ObjectId id)
{
var filter = Builders<T>.Filter.Eq("_id", id);
var result = collection.FindSync<T>(filter).FirstOrDefault();
return result;
}
The result when I connect to my Mongo DB in web config is the single entity by the Object Id - however when I change the connection string to the emulator nothing is returned?
This is how the object looks in MongoDB (visualized using RoboMongo)
{
"_id" : ObjectId("5b97a56b6381fecd00f0e10a"),
"LastUpdatedOn" : [
NumberLong(636722473812102569),
-240
],
"CreatedOn" : [
NumberLong(636722473396922518),
-240
],
"LastUpdatedBy" : "SYSTEM",
"CreatedBy" : "TestUser",
"VersionNumber" : 3,
"Name" : "Audi",
This is how the same object looks in the Azure Cosmos DB Emulator after the migration using the migration Data Tool
{
"_id": "5b97a56b6381fecd00f0e10a",
"LastUpdatedOn": [
636722473812102500,
-240
],
"CreatedOn": [
636722473396922500,
-240
],
"LastUpdatedBy": "SYSTEM",
"CreatedBy": "TestUser",
"VersionNumber": 3,
"Name": "Audi",
Could the reason it is not working be that that Id had lost the Object("")? I tried to update the Azure Cosmos DB collection to add that but it was giving an error saying value expected as if I wasn't specifying correct JSON format.
Upvotes: 0
Views: 1148
Reputation: 4009
The actual reason this was not working was using the Azure Cosmos DB Migration Too is designed for use with the Cosmos DB SQL API. I wanted to target the MongoDB API for Cosmos DB API.
The way to get the data into the Emulator for this was to use the mongoimport and mongoexport exe's as detailed here:
https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb-migrate
Upvotes: 0
Reputation: 7200
Judging from the CosmosDB emulator representation of the document it looks like you need to change your GetById method to use a string
instead of an ObjectId
.
Something like this should work:
public virtual T GetById(TKey id)
{
if (typeof(T).IsSubclassOf(typeof(EntityBase)))
{
return GetById(id as string);
}
//code removed for brevity
}
public virtual T GetById(string id)
{
var filter = Builders<T>.Filter.Eq("_id", id);
var result = collection.FindSync<T>(filter).FirstOrDefault();
return result;
}
Upvotes: 1