Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb c# driver LINQ vs Native query

Which of these queries is better performance wise one uses linq and the other uses a native querying mehanism

LINQ

var query =
collection.AsQueryable<Employee>()
.Where(e => e.FirstName == "John")
.Select(e => e); 


NATIVE

var query= Query<Employee>.EQ(e => e.FirstName, "John");
var emp = collection.FindOne(query);

I am assuming that the native querying mechanism in mongoDb would be better since, as far as I understand, it filters out the result in the database where as linq first gets all the items in the collection and then filters for the result.When should I consider using LINQ over native querying mechanism?

like image 208
Akshat Jiwan Sharma Avatar asked Oct 26 '12 07:10

Akshat Jiwan Sharma


People also ask

What is MongoDB C driver?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

Is MongoDB a C++?

Welcome to the documentation site for the official MongoDB C++ driver. You can add the driver to your application to work with MongoDB using the C++11 or later standard.

Is MongoDB free to use?

MongoDB Community is the source available and free to use edition of MongoDB. MongoDB Enterprise is available as part of the MongoDB Enterprise Advanced subscription and includes comprehensive support for your MongoDB deployment.


1 Answers

since, as far as I understand, it filters out the result in the database where as linq first gets all the items in the collection and then filters for the result

No, no and no. It filter everything on a database level.

Second one is not native way to build mongodb query. It is still same wrapper just build real native mongod query(for example {"a": 1, "b": 2 }).

First query use expression trees to build mongo query. Second one use reflection to build same query. As I know expression trees should be faster (here is first article I found). Anyway, I don't think that performance difference essential. So just use what you like more.

As for me, I use linq for most queries and some developers may even don't know much about mongo, but black side here is that you actually may not realize what query it can build for you. (the same situation with linq to sql for example). But you still be able to log all native queries, review them and find places for optimization, changes. For the complex queries I usually use second approach.

like image 80
Andrew Orsich Avatar answered Oct 13 '22 00:10

Andrew Orsich