I'm having trouble understanding how to do a findOne
operation in the Mongo C# 2.4 driver.
I have a collection with just over 9.1 million, flat documents. When I perform a findOne
in Robomongo, the query takes 0 seconds, and returns the result I wanted.
In C#, this takes about 7-8 seconds.
At present I'm implementing a find one like so:
var result = await _collection.Find(filterDefinition).SingleAsync();
This takes between 7 and 8 seconds.
Mongo Query - Find One - 0 seconds
.findOne({ipFrom: { $lte: 1436497981 }, ipTo: { $gte: 1436497981 }});
Mongo Query - Find - 7.4 seconds
.find({ipFrom: { $lte: 1436497981 }, ipTo: { $gte: 1436497981 }});
I can't find a FindOne
or FindOneAsync
method on IMongoCollection<>
, so I'm suspicious that .Find(...).SingleAsync()
is just performing a mongo find
function. I can see that there are FindOneAndUpdate
, FindOneAndDelete
, and FindOneAndReplace
, but no FindOne
.
My filter definition I'm using for the query is as follows:
var filter = Builders<TLocationEntity>.Filter;
var filterDefinition = filter.And(
filter.Lte("ipFrom", ipValue),
filter.Gte("ipTo", ipValue)
);
Basically, what's the correct way to do a findOne
in the C# driver?
A Cross Platform MongoDB Client Library for C. 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.
The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.
Now that libbson is compiled, let's install it using msbuild. It will be installed to the path specified by CMAKE_INSTALL_PREFIX . Now let's do the same for the MongoDB C driver. All of the MongoDB C Driver's components will now be found in C:\mongo-c-driver .
Adding Limit(1)
fixed it for me:
await _collection.Find(filterDefinition).Limit(1).SingleAsync();
I would have expected .SingleAsync()
to perform a Limit(1)
inside it, however it seems to perform a .Limit(2)
instead. This is enough to cause my query to go from 0 seconds to 8 seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With