Select Query With Logical Operator in a Mongo Database Using C# Driver

Description

In this article, I will describe how to do a select query in a Mongo database using a C# driver.

Content

As we know the Mongo DB offers a rich query environment with many features. This page lists some of those features.

Queries in Mongo DB are represented as JSON-style objects, very much like the documents we store in the database. For example.

// i.e., select * from things where id=3 and name="shir"
db.things.find({ id: 3, name: "shir" });

Now the Conditional Operators in a query are.

<, <=, >, >=

Now in this application, I want to fetch all the records of "AlertName" where the "alert id" is greater than 25.
Now it is time to create the application.

Step 1. Create a console application named "SelectQueryMOngodb".

Step 2. Now create a class named "NextMessage".

public class NextMessage
{
    public List<Dictionary<string, object>> GetAddress(int MessageId)
    {
        var AddressList = new List<Dictionary<string, object>>();
        for (int i = MessageId; i < MessageId + 9; i++)
        {
            Dictionary<string, object> message = new Dictionary<string, object>();
            message.Add("Id", i);
            message.Add("DateCreated", DateTime.Today.AddDays(i));
            message.Add("MessageType", "SAS");
            message.Add("AlertName", "Airtel" + i.ToString());
            AddressList.Add(message);
        }
        return AddressList;
    }
}

Here you see I passed the value into the dictionary.

Step 3. Now create a class named "DataProvider".

public class DataProvider
{
    MongoCollection<BsonDocument> nextMessages, om9Messages;
    MongoServer server;
    MongoDatabase oneConsoleDB;
    private void openConnection()
    {
        if (server.State == MongoServerState.Disconnected)
            server.Connect();
        oneConsoleDB = server.GetDatabase("AirMessage");
        if (!oneConsoleDB.CollectionExists("NextMessages"))
            oneConsoleDB.CreateCollection("NextMessages", null);
        nextMessages = oneConsoleDB.GetCollection("NextMessages");
    }
    public DataProvider()
    {
        string connectionString = "mongodb://192.168.40.27/?sockettimeout=5m";
        server = MongoServer.Create(connectionString);
    }
    public void InsertBatch()
    {
        openConnection();
        nextMessages.RemoveAll();
        var netxMessageBatch = BsonSerializer.Deserialize<BsonDocument[]>(new NextMessage().GetAddress(20).ToJson());
        var test = netxMessageBatch.Where(t => t.Elements.ElementAt(3).Value.Equals("NetxFM23"));
        nextMessages.InsertBatch(netxMessageBatch);
        Console.WriteLine("Inserted successfully");
        server.Disconnect();
        Console.ReadLine();
    }
    public void GetNetxMessageByCriteria(int alertId)
    {
        openConnection();
        StringBuilder str1 = new StringBuilder("{\"Id\":{$gt : " + alertId.ToString() + "}}");
        string st = "AlertName,Id";
        var query1 = new QueryDocument(BsonSerializer.Deserialize<BsonDocument>(str1.ToString()));
        var docs = nextMessages.Find(query1).SetFields(st.Split(','));
        Console.WriteLine(docs.ToList().ToJson());
        server.Disconnect();
        Console.ReadLine();
    }
    public class NextMessage
    {
        public List<Dictionary<string, object>> GetAddress(int MessageId)
        {
            var AddressList = new List<Dictionary<string, object>>();
            for (int i = MessageId; i < MessageId + 9; i++)
            {
                Dictionary<string, object> message = new Dictionary<string, object>();
                message.Add("Id", i);
                message.Add("DateCreated", DateTime.Today.AddDays(i));
                message.Add("MessageType", "SAS");
                message.Add("AlertName", "Airtel" + i.ToString());
                AddressList.Add(message);
            }
            return AddressList;
        }
    }
}

See in the DataProvider method I supplied my system IP address. In your case, you have to write your system IP address to connect to the database.

var netxMessageBatch = BsonSerializer.Deserialize<BsonDocument[]>(new NextMessage().GetAddress(20).ToJson());

Here whatever dictionary data we are getting from the "NextMessage" class, we have to Deserialize it before putting it into the Mongo database.

Now the following code is for saving the dictionary data into the Mongo db.

nextMessages.InsertBatch(netxMessageBatch);

Now see the "GetNetxMessageByCriteria" method. Here I have written the select query.

First I wrote the query in the stingbuilder then I passed the query to the "QueryDocument". After that in the "Find" Method, I am passing the query.

StringBuilder str1 = new StringBuilder("{\"Id\":{$gt : " + alertId.ToString() + "}}");
string st = "AlertName, Id";
var query1 = new QueryDocument(BsonSerializer.Deserialize<BsonDocument>(str1.ToString()));
var docs = nextMessages.Find(query1).SetFields(st.Split(','));
Console.WriteLine(docs.ToList().ToJson());

So here the query will return all the AlertNAme where the alert ID is greater than 25.

In SQL the query looks like.

Select the alert name from the table where alerted>25.

Step 5. Now in the main program write the following code.

class Program
{
    static void Main(string[] args)
    {
        DataProvider dp = new DataProvider();
        dp.InsertBatch();
        dp.GetNetxMessageByCriteria(25);
        Console.WriteLine();
    }
}

Step 6. Now open the "MOngoGod.exe" and run the application; it will look like the following figure.

Conclusion

So in this article, we have learned how to do an insert query in a Mongo db using a C# driver.


Similar Articles