Creating a database and collection programmatically for Azure Cosmos DB via Mongo DB .NET Driver - mongodb

I am using the .NET MongoDb driver and Azure Cosmos DB Emulator. I am trying to create a database and collection on startup of a dotnet core Web Api project.
I am running the following code within the ConfigureServices function in Startup.cs.
var connectionString = databaseConfig.GetValue<string>("connectionString");
var databaseName = databaseConfig.GetValue<string>("name");
var client = new MongoClient(connectionString);
var db = client.GetDatabase(databaseName);
var collection = db.GetCollection("users");
This is neither creating the database or the collection. I am viewing this in the emulator's data explorer and Robo3T client.
I was under the impression that client.GetDatabase(databaseName) and db.GetCollection<User>("users") will create if the database and collection does not exist respectively.
I can get it to create the database and collection with the following db.CreateCollection("users"). This will require me to check if the collection first exists and isn't the prescribed approach.
Does anyone have any insights into this behaviour?
Thanks.

If you insert a document, the collection gets created, don't ask why!

Related

Is there a way to create a collection with partitionKey/shardKey in Azure Cosmos DB for Mongo API using Java?

I'm trying to create a collection with shard key in Azure Cosmos DB for Mongo API, but this code throws an error as com.microsoft.azure.documentdb.DocumentClientException: Partition key path /partKey is invalid for MongoDB API.
public void createCollections(String collectionNames, String dbName, int throughput, String partitionKey) throws DocumentClientException{
DocumentCollection curCol = new DocumentCollection();
curCol.setId(collectionNames);
ArrayList<String> paths = new ArrayList<String>();
paths.add(partitionKey);
PartitionKeyDefinition partDef = new PartitionKeyDefinition();
partDef.setPaths(paths);
curCol.setPartitionKey(partitionKey);
RequestOptions reqOp = new RequestOptions();
reqOp.setOfferThroughput(throughput);
try (DocumentClient db = this.getDocClient(this.getAccountEndPoint(), this.getAccountKey())) {
db.createCollection(DBLINK + dbName, curCol, reqOp);
}
}
Is there is any way to create one?
You are using the Azure Cosmos DB Java SDK to create a MongoDB resource. That SDK only works with SQL API accounts in Cosmos DB.
To work with MongoDB API resources in Cosmos DB, you need to use native MongoDB drivers. To use these drivers to create and manage MongoDB resources in Cosmos DB you use the MongoDB extension commands for Cosmos DB. These provide the options to specify throughput, shard keys, etc.
Here is a Java example to create a collection for the MongoDB API for Cosmos DB. Apologies for poor Java usage, been a while since I wrote any.
String uri = "<connection string uri>";
MongoClient mongoClient = MongoClients.create(uri)
MongoDatabase database = mongoClient.getDatabase("myDatabase");
Document doc = new Document("customAction", "CreateCollection")
.append("collection", "myCollectionName")
.append("shardKey", "partKey")
.append("offerThroughput", 400);
Document commandResult = database.runCommand(doc);
System.out.println("dbStats: " + commandResult.toJson());

Azure Function data to Mongo Db

I have created an Azure function which fetches data from a particular API. I want to now insert the data fetch from API in MONGO database but I have no idea how to proceed.
Please help!!
Also let me know if there is any other information needed
First you have to create a mongo db database either in azure or in mongo and get the connection string of the database. In case of azure create a azure cosmos db api for mongo dB resource from the portal and get the connection string.
Theoretically here we create a client object (here we also pass the connection string) which will connect to the mongo db then we will use the client to create and manipulate the database.
Under the quickstart tab of the azure mongo dB you will find language specific ways to create the client and ways to change the database.
Now using the connection string, we can connect to the mongo dB. Since you are using azure function use the application setting to store the connection string and use them as an environment variable. The application setting is under configuration tab.
Refer this article by Robert Walters

how to export current app users from mongo realm application?

My question is a simple query regarding mongo realm application. How can we export the current app users from mongo realm application.
I am trying to clone an existing mongo realm application
I have successfully exported the mongo atlas db dump as well as the mongo realm application
I have successfully created new mongo realm application and imported all the previous existing setup
I am able to see the users collection in my mongo altas collection but when trying to login with there cred it shows user not exists
Please also note I am using default authentication i.e., "Email/Password"

Access Meteor Collections from MongoDB Issue?

I have created & deploy one app using Meteor. The deploy name myapp.meteor.com. I have connected to Mongo DB using the below procedure:
Command Prompt From Meteor :
Meteor mongo myapp.meteor.com
//Below one is Response from Meteor mongo myapp.meteor.com command
MongoDB shell version: 2.4.8
connecting to: production-db-b3.meteor.io:27017/myapp_meteor_com
Command Prompt From MongoDB:
use myapp_meteor_com
I have created Emp collection using myapp code.From Mongo DB command prompt i will try to see collections to created from myapp But it doesn't show.And i am using to show collections using below procedure:
connecting to: test
> show dbs
myapp_meteor_com (empty)
local 0.078125GB
> use myapp_meteor_com
switched to db myapp_meteor_com
> show collections //here shows nothing but js file contains `Emp Collection` and data inserted as shown below.
> //here no collections shows.
So i didn't have any idea show please suggest me what to do for above problem?
//Here data inserted to Emp collection obj.
JS Code :
if (Meteor.isServer)
{
Meteor.startup(function ()
{;
if (Emp.find().count() === 0)
{
for (var i = 0; i < 10; i++)
Emp.insert({ fname: "xxx",userid: i, email : "abc#gmail.com"});
}
});
}
You may have created collections using Emp = new Meteor.Collection("emp") (if you did this).
The thing is that the collections will only be created if you insert data into them. If you create a collection in the way like above, you've only declared it as a variable and the collection will not appear in mongodb.
This is generally how mongodb works: The collections are created automatically when you insert data into them.

Mongo admin database credentials don't work in other databases on server

The documentation for Mongo states that when authentication is enabled, and for users added to the admin database, these users should be able to access the other databases in Mongo, with the rights granted at the admin database level.
"The admin database is unique. Users with normal access to the admin database have read and write access to all databases. Users with read only access to the admin database have read only access to all databases." http://docs.mongodb.org/manual/administration/security/
But in testing with the C# library version 1.7.0.4714, this is not the case.
Only accounts created in a specific database have access to that database.
I have tested with credentials on the connection string
and by setting credentials explicitly at the database level in C#
server.GetDatabase(...
new MongoClient(a connectionString ...
Does anyone know if this expected behavior? or can suggest a resolution.
The answer was already posted here on stackoverflow :)
Mongodb C# driver - can't use admin authentication to access other databases
the username used should have (admin) after it to use that account.
This is not a mongodb problem. I am sure that you could authenticate from mongodb shell like this:
use admin
db.auth(user, pass)
This is a mongodb c# driver trick. A long time ago i spent some time to read c# driver code in order to understand this.
So connection string should be like this:
mongodb://admin(admin):1#localhost:27020/myDb
The trick in (admin) in order to tell the driver that you are going to authenticate via admin user.
There is another way to connect with authentication against the admin database.
The downside is that you have to setup the whole connection object instead of packing all info solely on a connection string.
Instead of instantiating the MongoClient with a connection string like
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
you can create a MongoClientSettings object, set the credentials (along with any other connection settings) and instantiate the client passing that object
string authenticationDB = "admin"
string authenticationUsername = "user"
string authenticationPassword = "pass"
MongoClientSettings settings = new MongoClientSettings();
settings.Credentials = new[] { MongoCredential.CreateMongoCRCredential(authenticationDB, authenticationUsername, authenticationPassword) };
settings.Servers = new[] { new MongoServerAddress("host_1"), new MongoServerAddress("host_2"), new MongoServerAddress("host_3") };
settings.ConnectionMode = ConnectionMode.ReplicaSet;
var client = new MongoClient(settings);
var db = client.GetServer().GetDatabase(database);
http://docs.mongodb.org/ecosystem/tutorial/authenticate-with-csharp-driver/