[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Behavior of createIndex for an existing index and tags: ['indexes']

[User]
Text:Hi,
What is the mongo behavior when a createIndex command is reissued for an existing index on an existing collection?
We use spring-mongo to interact with the db and are using @indexed for index creation in application. This means that the  createIndex command is reissued every time the application starts up. Is there a performance overhead from this? I would expect this to get ignored by mongo but would love to get a clarification since i couldnt find anything concrete in the documentation.
Appreciate any leads. Thanks!
Code:

[Assistant]
Text:From mongo documentationIf you call  db.collection.createIndex()  for an index that already exists, MongoDB does not recreate the index.
Code:db.collection.createIndex()

[User]
Text:Is this applicable for older mongo versions? We use 3.6 and 4.0
Code:

[Assistant]
Text:Hi @Sneh_Bharati,Behaviour for attempted re-creation of an existing index is the same in older versions of MongoDB. Create index commands will not recreate existing indexes and instead return a success message indicating “all indexes already exist” (the underlying server createIndexes command supports creating one or more indexes).However, since you are using MongoDB 3.6 and 4.0 there is an important caveat if your application is ensuring indexes on startup. The default behaviour is to build new indexes in the foreground, which can have significant consequences for a production environment.Foreground index builds on a populated collection in MongoDB 4.0 and older will block all other operations on the database that holds the collection, so you would not want to accidentally have lengthy index builds start unless you also have a planned maintenance window.To avoid this issue you can either set the background property to true in your Spring index annotation using @Indexed(background=true), or use an admin strategy like rolling index builds for a replica set or sharded cluster. See: Index Build Operations on a Populated Collection (MongoDB 4.0).MongoDB 4.2+ uses an optimised index build process to minimise the impact on a production deployment. Collection-level locks are briefly held at the beginning and end of the process, but the rest of the index build runs as a background task. See: Index Builds on Populated Collections (MongoDB 4.2).Unfortunately Spring Data does not currently provide a way to set a global default for background indexes. A relevant issue to upvote and watch is DATAMONGO-1895: Add option to specify default background index building in AbstractMongoConfiguration in Spring Data’s issue tracker.Regards,
Stennie
Code:createIndexesbackgroundtrue@Indexed(background=true)

[Assistant]
Text:I think yes
You can try it out on some test DB/collectionI tested it on 4.0.5First run created new index
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1Second run when i try to create index on same field“numIndexesBefore” : 2,
“numIndexesAfter” : 2,
“note” : “all indexes already exist”,
“ok” : 1
Code:

[User]
Text:he default behaviour is to build new indexes in the foreground, which can have significant consequences for a production environment.Foreground index builds on a populated collection in MongoDB 4.0 and older will block all otherSpring data does allow passing an optional parameter to specify indexing in background vs foreground. I havent tried it out yet - but thats what we are planning to do going forward.
Thanks for your help.
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Connect timeout and execution timeout in nodejs driver and tags: ['node-js']

[User]
Text:Hi Guys! I hope I’m posting this in correct place…I’m working with MongoDB using NodeJS mongodb driver. But I can’t make few options to work… My setup:
OS: Windows 10 x64
NodeJS mongodb driver: 3.5.5
MongoDB: 4.2.5I want to limit:Description of connectTimeoutMS from mongodb.github.io: How long to wait for a connection to be established before timing outDescription from jira.mongodb.org: dictates how long to wait for an initial connection before considering it a timeout. This is used exclusively when we create a TCP/TLS socketSo I tried to connect to disabled DB with the following code:Which produces the following logs:If I will change useUnifiedTopology to false I will get this log:The issue that I have connectTimeoutMS set to 5 000 ms (5 secs) but as you can see it gets timed out in 2 or 30 seconds not in 5 seconds.Next issue is with query execution timeout.Description of socketTimeoutMS from mongodb.github.io: How long a send or receive on a socket can take before timing outDescription from jira.mongodb.org: dictates how long to wait for any operation on an existing connection before timing out. Once the TCP socket has been connected, we use this for our actual operationsSo I tried to make a query into DB with 5 seconds timeout limit:And I got this:I though that after 5 secs I will get timeout error… What’s wrong ?
Even if I will set socketTimeoutMS to 30 ms I will get the same result…
But if I will set it to 20 ms I will get this:If I replace find with count (collection has more than 10 millions docs) and use await coll.countDocuments() I will get Timeout Error after 60 secs (not after 5)Can anybody assist me, I dont understand what’s going on…
Code:const { MongoClient } = require('mongodb')

const url = 'mongodb://localhost'
const config = {
  connectTimeoutMS: 5000,
  useUnifiedTopology: true
}

async function mongodb() {
  console.time('connect')
  try { await MongoClient.connect(url, config) }
  catch (error) { console.error(error) }
  finally { console.timeEnd('connect') }
}

mongodb()
MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
connect: 30034.340ms
(node:19040) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017

connect: 2025.937ms
const { MongoClient } = require('mongodb')

const fetchLimit = 500000
const url = 'mongodb://localhost'
const config = {
  connectTimeoutMS: 5000,
  socketTimeoutMS: 5000,
  useUnifiedTopology: true
}

async function mongodb() {
  let client

  console.time('connect')
  try { client = await MongoClient.connect(url, config) }
  catch (error) { console.error(error) }
  finally { console.timeEnd('connect') }

  const coll = client.db('reps').collection('req')

  console.time('find')
  try { await coll.find({ p: 'XYZ' }).limit(fetchLimit).toArray() }
  catch (error) { console.error(error) }
  finally { console.timeEnd('find') }
}

mongodb()
connect: 28.459ms
find: 8731.263ms
connect: 70.304ms
MongoNetworkError: connection 2 to 127.0.0.1:27017 timed out
find: 1225.078ms
findcountawait coll.countDocuments()

[Assistant]
Text:Hi @Vlad_Kote, welcome to the community forums! I’ll try to answer your questions in two sections below:The connectTimeoutMS option is used by the driver to determine when to timeout an attempt to connect an individual connection to a server (one of many in your connection pool). It does not have a direct relation to MongoClient#connect. When you attempt to connect a MongoClient it attempts server selection, which means that it will attempt for up to serverSelectionTimeoutMS to connect to the cluster before reporting that it was unable to find a suitable server.If you want to get “fast fail” behavior on your connect, you can pass serverSelectionTimeoutMS to your MongoClient:The socketTimeoutMS option corresponds to Node’s Socket#setTimeout method, and guides the behavior around socket inactivity. In your case it seems like you want to guarantee that an operation succeeds or fails in a given time range. Your best bet for this today is to use a combination of socketTimeoutMS (in case the socket is indeed inactive, due to network issues) and maxTimeMS which will cause the operation to fail after the specified time on the server side:in this case will result in:Hope that helps!
Code:connectTimeoutMSMongoClient#connectMongoClientserverSelectionTimeoutMSserverSelectionTimeoutMSMongoClientconst client = new MongoClient(..., { serverSelectionTimeoutMS: 5000 });
await client.connect();
socketTimeoutMSsocketTimeoutMSmaxTimeMStry {
  const collection = client.db().collection('test_collection');

  console.time('find');
  await collection.find({ $where: 'sleep(1000)' }).limit(10).maxTimeMS(10).toArray();
  console.timeEnd('find');
} catch (err) {
  console.timeEnd('find');
  console.dir({ err });
}
find: 44.282ms
{
  err: MongoError: operation exceeded time limit
      at MessageStream.messageHandler (/home/mbroadst/Development/mongo/node-mongodb-native/lib/cmap/connection.js:261:20)
      at MessageStream.emit (events.js:209:13)
      at processIncomingData (/home/mbroadst/Development/mongo/node-mongodb-native/lib/cmap/message_stream.js:144:12)
      at MessageStream._write (/home/mbroadst/Development/mongo/node-mongodb-native/lib/cmap/message_stream.js:42:5)
      at doWrite (_stream_writable.js:428:12)
      at writeOrBuffer (_stream_writable.js:412:5)
      at MessageStream.Writable.write (_stream_writable.js:302:11)
      at Socket.ondata (_stream_readable.js:722:22)
      at Socket.emit (events.js:209:13)
      at addChunk (_stream_readable.js:305:12) {
    ok: 0,
    errmsg: 'operation exceeded time limit',
    code: 50,
    codeName: 'ExceededTimeLimit',
    operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1585574598 },
    '$clusterTime': { clusterTime: [Timestamp], signature: [Object] },
    name: 'MongoError',
    [Symbol(mongoErrorContextSymbol)]: {}
  }
}

[User]
Text:Thanks a lot,  @mbroadst !And yes, ‘serverSelectionTimeoutMS’ exactly what I need.
And ‘maxTimeMS’ method also did the trick here…Looks like I was confused from the beginning…
I’m working with Mongoose lib which has clear notice in the docs that “we pass Option object into underlying mongodb lib”. But I didn’t find such notice in mongodb lib. That’s why I thought that mongodb couldn’t handle it…So serverSelectionTimeoutMS option is handled by… By whom ? The mongodb lib source uses that param but I can’t find mention about it in their docs mongodb.github.io/node-mongodb-native/3.5/api/. Am I looking in wrong place ?Lib docs hasn’t Connection SettingsBut the MongoDB docs itself has…I will try now to achieve what I want with Mongoose.Again, thanks a lot, @mbroadst
Code:

[Assistant]
Text:Glad to hear it helped!You’re not crazy, our documentation is not helping you out right now - but we’re working on that:serverSelectionTimeoutMS is a top-level MongoClient or connection string option that is only supported by the “Unified Topology”. Since this topology is still gated by a feature flag, its documentation was not merged in with MongoClient. In the next patch release of the driver these options will be added, with a note that they are only relevant to the unified topology.We are currently introducing type checking to the driver, which will result in much higher quality API documentation, and intellisense if you happen to be using an editor with LSP supportFinally, we have a larger project in place to rewrite our Reference documentation to include in-depth details on topics such as this. The project is being handled by our fantastic documentation team, so you can expect to have a better experience with our documentation in the future.
Code:serverSelectionTimeoutMSMongoClientMongoClient


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: MongoDB won't start as a windows service, but will start at the command line and tags: ['configuration']

[User]
Text:Hi
I have been using MongoDB Community edition (version mongodb-win32-x86_64-2012plus-4.2.5-signed) on my PC until yesterday, running Windows 10.  Not sure if this is relevant, but for background I am accessing the same DB from a laptop (same versions of MongoDB and Windows10), not at the same time (!), so that I can do development work at home or when away.  I have the MongoDB files set up in a folder that is mirrored across devices using sync.com (similar to Dropbox).  This has worked all worked fine until yesterday.Yesterday mongoDB would not start as a service on my main PC (note it continues to work fine on my laptop - the service starts and I can access the db no problem).  I have tried various options suggested on the internet including --repair, trying to give admin permissions to everything (although think this is unnecessary because it worked without special permissions before and from what I can see most recommendations about this are the unix/linux installs) and finally I have done a full uninstall and clean install.  I am at a point where the Windows service will not start, nor will it work if I run it from the command line… unless I remove the --server option and then it works fine.So, if I run the following at the command line the service doesn’t start (this is copied and pasted from the Windows services “path to executable”):
“C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe” --config “C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg” --serviceHowever, if I run the following at the command line then it works fine and I am able to connect using Compass/run my app:
“C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe” --config “C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg”Note this is running in the command prompt without admin rights in both cases, which I think suggests this isn’t a rights issue(?)The log file for the failed start isn’t very informative (to me at least, but then I am completely new to this!)  I have included the log below that includes both the failed start using the --server option and then a successful run with the --server option removed.  Note I have inserted a blank line between the two runs just for clarity.And finally, if I start the service via the Windows Services app I get error 1053 as per the screenshot below.  If I look in the Windows Event Viewer (Windows Logs\System) there are two entries for this.  One with the message below and the second says, “A timeout was reached (30000 milliseconds) while waiting for the MongoDB Server service to connect.” (although it takes less than a couple of seconds to fail, not the 30 seconds this suggests).Does anyone have any suggestions as to why this is happening and how I can fix it?
Code:2020-03-31T08:53:51.977+0100 I  CONTROL  [main] ***** SERVER RESTARTED *****
2020-03-31T08:53:51.982+0100 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-03-31T08:53:52.850+0100 W  ASIO     [main] No TransportLayer configured during NetworkInterface startup
2020-03-31T08:53:52.851+0100 I  CONTROL  [main] Trying to start Windows service 'MongoDB'

2020-03-31T08:54:12.058+0100 I  CONTROL  [main] ***** SERVER RESTARTED *****
2020-03-31T08:54:12.889+0100 I  CONTROL  [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2020-03-31T08:54:12.894+0100 W  ASIO     [main] No TransportLayer configured during NetworkInterface startup
2020-03-31T08:54:12.895+0100 I  CONTROL  [initandlisten] MongoDB starting : pid=6892 port=27017 dbpath=C:\Users\Bob\Sync\Programming\MongoDB\data 64-bit host=Music-PC
2020-03-31T08:54:12.895+0100 I  CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2020-03-31T08:54:12.895+0100 I  CONTROL  [initandlisten] db version v4.2.5
2020-03-31T08:54:12.895+0100 I  CONTROL  [initandlisten] git version: 2261279b51ea13df08ae708ff278f0679c59dc32
2020-03-31T08:54:12.896+0100 I  CONTROL  [initandlisten] allocator: tcmalloc
2020-03-31T08:54:12.896+0100 I  CONTROL  [initandlisten] modules: none
2020-03-31T08:54:12.896+0100 I  CONTROL  [initandlisten] build environment:
2020-03-31T08:54:12.896+0100 I  CONTROL  [initandlisten]     distmod: 2012plus
2020-03-31T08:54:12.896+0100 I  CONTROL  [initandlisten]     distarch: x86_64
2020-03-31T08:54:12.896+0100 I  CONTROL  [initandlisten]     target_arch: x86_64
2020-03-31T08:54:12.896+0100 I  CONTROL  [initandlisten] options: { config: "C:\Program Files\MongoDB\Server\4.2\bin\mongod.cfg", net: { bindIp: "127.0.0.1", port: 27017 }, storage: { dbPath: "C:\Users\Bob\Sync\Programming\MongoDB\data", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "C:\Users\Bob\Sync\Programming\MongoDB\log\mongod.log" } }
2020-03-31T08:54:12.900+0100 I  STORAGE  [initandlisten] Detected data files in C:\Users\Bob\Sync\Programming\MongoDB\data created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2020-03-31T08:54:12.901+0100 I  STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=3582M,cache_overflow=(file_max=0M),session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress],
2020-03-31T08:54:13.006+0100 I  STORAGE  [initandlisten] WiredTiger message [1585641253:6456][6892:140724896882256], txn-recover: Recovering log 17 through 18
2020-03-31T08:54:13.164+0100 I  STORAGE  [initandlisten] WiredTiger message [1585641253:164656][6892:140724896882256], txn-recover: Recovering log 18 through 18
2020-03-31T08:54:13.362+0100 I  STORAGE  [initandlisten] WiredTiger message [1585641253:361919][6892:140724896882256], txn-recover: Main recovery loop: starting at 17/7808 to 18/256
2020-03-31T08:54:13.654+0100 I  STORAGE  [initandlisten] WiredTiger message [1585641253:653905][6892:140724896882256], txn-recover: Recovering log 17 through 18
2020-03-31T08:54:13.812+0100 I  STORAGE  [initandlisten] WiredTiger message [1585641253:812105][6892:140724896882256], txn-recover: Recovering log 18 through 18
2020-03-31T08:54:13.959+0100 I  STORAGE  [initandlisten] WiredTiger message [1585641253:958585][6892:140724896882256], txn-recover: Set global recovery timestamp: (0, 0)
2020-03-31T08:54:13.992+0100 I  RECOVERY [initandlisten] WiredTiger recoveryTimestamp. Ts: Timestamp(0, 0)
2020-03-31T08:54:14.001+0100 I  STORAGE  [initandlisten] Timestamp monitor starting
2020-03-31T08:54:14.012+0100 I  CONTROL  [initandlisten]
2020-03-31T08:54:14.013+0100 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-03-31T08:54:14.013+0100 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-03-31T08:54:14.013+0100 I  CONTROL  [initandlisten]
2020-03-31T08:54:14.023+0100 I  SHARDING [initandlisten] Marking collection local.system.replset as collection version: <unsharded>
2020-03-31T08:54:14.027+0100 I  STORAGE  [initandlisten] Flow Control is enabled on this deployment.
2020-03-31T08:54:14.027+0100 I  SHARDING [initandlisten] Marking collection admin.system.roles as collection version: <unsharded>
2020-03-31T08:54:14.027+0100 I  SHARDING [initandlisten] Marking collection admin.system.version as collection version: <unsharded>
2020-03-31T08:54:14.031+0100 I  SHARDING [initandlisten] Marking collection local.startup_log as collection version: <unsharded>
2020-03-31T08:54:14.501+0100 I  FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/Users/Bob/Sync/Programming/MongoDB/data/diagnostic.data'
2020-03-31T08:54:14.503+0100 I  SHARDING [LogicalSessionCacheRefresh] Marking collection config.system.sessions as collection version: <unsharded>
2020-03-31T08:54:14.504+0100 I  NETWORK  [listener] Listening on 127.0.0.1
2020-03-31T08:54:14.504+0100 I  SHARDING [LogicalSessionCacheReap] Marking collection config.transactions as collection version: <unsharded>
2020-03-31T08:54:14.504+0100 I  NETWORK  [listener] waiting for connections on port 27017
2020-03-31T08:54:15.005+0100 I  SHARDING [ftdc] Marking collection local.oplog.rs as collection version: <unsharded>
2020-03-31T08:55:47.470+0100 I  CONTROL  [thread1] Ctrl-C signal
2020-03-31T08:55:47.470+0100 I  CONTROL  [consoleTerminate] got CTRL_C_EVENT, will terminate after current cmd ends
2020-03-31T08:55:47.471+0100 I  NETWORK  [consoleTerminate] shutdown: going to close listening sockets...
2020-03-31T08:55:47.472+0100 I  -        [consoleTerminate] Stopping further Flow Control ticket acquisitions.
2020-03-31T08:55:47.472+0100 I  CONTROL  [consoleTerminate] Shutting down free monitoring
2020-03-31T08:55:47.473+0100 I  FTDC     [consoleTerminate] Shutting down full-time diagnostic data capture
2020-03-31T08:55:47.477+0100 I  STORAGE  [consoleTerminate] Deregistering all the collections
2020-03-31T08:55:47.477+0100 I  STORAGE  [consoleTerminate] Timestamp monitor shutting down
2020-03-31T08:55:47.477+0100 I  STORAGE  [consoleTerminate] WiredTigerKVEngine shutting down
2020-03-31T08:55:47.477+0100 I  STORAGE  [consoleTerminate] Shutting down session sweeper thread
2020-03-31T08:55:47.478+0100 I  STORAGE  [consoleTerminate] Finished shutting down session sweeper thread
2020-03-31T08:55:47.478+0100 I  STORAGE  [consoleTerminate] Shutting down journal flusher thread
2020-03-31T08:55:47.577+0100 I  STORAGE  [consoleTerminate] Finished shutting down journal flusher thread
2020-03-31T08:55:47.577+0100 I  STORAGE  [consoleTerminate] Shutting down checkpoint thread
2020-03-31T08:55:47.577+0100 I  STORAGE  [consoleTerminate] Finished shutting down checkpoint thread
2020-03-31T08:55:47.698+0100 I  STORAGE  [consoleTerminate] shutdown: removing fs lock...
2020-03-31T08:55:47.698+0100 I  CONTROL  [consoleTerminate] now exiting
2020-03-31T08:55:47.699+0100 I  CONTROL  [consoleTerminate] shutting down with code:12

[User]
Text:I don’t know what the root cause is, but I appear to have fixed the problem.I had set the database service to startup using the NetworkService account in Windows, which I think was the default as part of the installation process (I wouldn’t swear to it, but I don’t know enough about it to change the option).  I have now changed this to use the Local System account option and the service now starts and works without any problems.  I have other services running as the NetworkService user to not sure why this is an issue.Path to change things:
Press Cmd+R keys to bring up start menu
Type services and run the app
Locate MongoDB Server, right-click and select Properties
Access LogOn tab
Select Local System account radio button
Select OKJob done.  I don’t know what problems this might cause me later, but I’ll deal with that when I get to it.
Code:NetworkServiceLocal System accountNetworkServiceCmd+RservicesMongoDB ServerPropertiesLogOnLocal System accountOK


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: MongoDB raspberry pi 4 docker image? and tags: ['containers', 'installation']

[User]
Text:I want to setup a raspberry pi 4 as a MongoDB server.
The latest official mongoDB docker image does not support the raspberry pi 4 arhitecture.
Is there any docker image you would recommend I should use?
(The one I found available and working was 2.4.0 version, I would prefer to work with a more newer version, mostly because I’m just starting to work with this.)
**Note that I’m a starter in docker, mongodb, raspberry.
Code:

[Assistant]
Text:Welcome to the community @Emil_Marian_Pasca!What O/S version are you running on your Pi 4? WiredTiger, the default storage engine since MongoDB 3.2, requires a 64-bit O/S.Given the Pi has limited resources I would be inclined to install packages directly rather than using Docker.As an alternative to installing a MongoDB server on your Pi, you could also consider using the MongoDB Atlas free tier to get started quickly.Regards,
Stennie
Code:

[User]
Text:Thanks for your suggestions, my specs are:
Linux piOne 4.19.75-v7l+  BST 2019 armv7l GNU/Linux
Distributor ID: Raspbian
Description:    Raspbian GNU/Linux 10 (buster)
Release:        10
Codename:    busterI’ve switch to the MongoDB Atlass free tier, which suits my current needs, as I’m just following the MongoDB university lessons.
However, I like to have a local sandbox for testing purposes on my raspberry pi, docker helps me keep the OS clean and easy to manage, I would probably consider installing it directly if my project requires this.I have just figured out that I am running a 32 bit O/S. So this is probably the reason I could not install a later version of MongoDB.
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Windows PHP startup error - unable to find module and tags: ['php']

[User]
Text:help please.
i have windows 10 php 7 and mysql installed and all working fine.
i installed mongodb database and its operational, tested using compass.
i am now trying to use it from within php. i have used it before on an older machine successfully.
i downloaded mongodb.dll threadsafe64 - i thought the right one.
i put the extension parameter into ini file - =mongodb.dll
and then restarted all wamp services.
mongo driver is not loading and no sign in phpinfo().
in the php error log it says not found [di]r/mongodb.dll unable to load module.
i gathered this could be becuae i had installed the wrong version? i changed the name in the ini file to a rubbish name  and tried again, same message.
the filename is correct and its in the right directory .
i then downlaoded a 32bit version (same name obviously) to see what would happen. this time it got a different message - about being wrong type. so its definitly going to the right place.any ideas?
all i can now think of is that i am using the wrong wrong version of the dll, i tried to check the right version of the dll for php v7 but i couldnt trace what that should be.
do i  need to put the pdb file there also?thanks
Code:

[User]
Text:exact error msg is
PHP Startup: Unable to load dynamic library ‘C:\wamp64\bin\php\php7.0.10\ext\php_mongodb.dll’ - The specified module could not be found.in Unknown on line 0the mongodb.dll version is  7.4.0
Code:

[Assistant]
Text:If the file is indeed in the exact path given above, then “the module could not be found” may not refer to the MongoDB extension itself, but one of its dependencies. As outlined in the Windows installation docs, the extension needs libsasl.dll to be found in the operating system’s PATH. Please check if the file is in the path and change the configuration if it isn’t. Thanks!
Code:libsasl.dllPATH

[User]
Text:manyh thanks. i started looking as you suggested, then found a different version of the driver. i tried that and it all burst into life!many thanks for responding.it seems so hard to find  proper list of dlls per php version per platform.need to try PI next!
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: How get the ToList() of objects from MongoDB to C# and tags: ['dot-net']

[User]
Text:List<Models.RootObject1>  bsonPlanData2 = collection.AsQueryable().Where(e1 => e1.wsId == WSId).Select(e => new  { e.nodeHierarchy, e.Parentnode,e.wsId,e.dateFrom,e.dateTo,e.IsLeafNode,e.weightage }).ToList();List<Models.RootObject1>  bsonPlanData2 = collection.AsQueryable().Where(e1 => e1.wsId == WSId).Select(e => new  { e.nodeHierarchy, e.Parentnode,e.wsId,e.dateFrom,e.dateTo,e.IsLeafNode,e.weightage }).ToList();List<Models.RootObject1>  bsonPlanData2 = collection.AsQueryable().Where(e1 => e1.wsId == WSId).Select(e => { e.nodeHierarchy, e.Parentnode,e.wsId,e.dateFrom,e.dateTo,e.IsLeafNode,e.weightage }).ToList();List<Models.RootObject1>  bsonPlanData2 = collection.AsQueryable().Where(e1 => e1.wsId == WSId).Select(e => new RootObject1() { e.nodeHierarchy, e.Parentnode,e.wsId,e.dateFrom,e.dateTo,e.IsLeafNode,e.weightage }).ToList();above 4 ways are there, where i tried to get the data from mongo and put it in my c# object.
though there is one newtonsoft deserializer is there , but somebody told me that my 4 call also deserializes, so i do not want to use extra conversion by usng newtornsoft desrilizer.and above code shows me that u have to implemnt ienumerator in my class. so pls tel me is there any othe way i could do this with out implimenting ienumertoe in my class.
Code:public class RootObject1
    {

        public Dictionary<string, string> nodeHierarchy { get; set; }
        public Dictionary<string, string> Parentnode { get; set; }
        public string wsId { get; set; }
        public DateTime dateFrom { get; set; }
        public DateTime dateTo { get; set; }
        public bool IsLeafNode { get; set; }
        public decimal weightage { get; set; }
}
/**
* this is what i have in mongodb
* Paste one or more documents here
*/
{
    "Parentnode": {
        "LEVEL1": "Civil and Structural",
        "LEVEL2": "Cluster 1",
        "LEVEL3": "Workshop & Maintenance Building"
    },
    "nodeHierarchy": {
        "LEVEL1": "Civil and Structural",
        "LEVEL2": "Cluster 1",
        "LEVEL3": "Workshop & Maintenance Building",
        "LEVEL4": "Excavation"
    },
    "weightage": "20",
    "dateFrom": "2019-01-01",
    "dateTo": "2019-12-31",
    "IsLeafNode": true,
    "wsId": "PROJECT2"
}


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: How to optimize countDocuments() and tags: ['queries', 'performance']

[User]
Text:Hello! We are having some performance issues with our countDocuments() query as it is taking > 17 seconds (our client-side timeout is 17s) for most queries to complete execution during our load testing. This is only happening during load testing and the query returns in ~300ms when the system is not under load. This query, in particular, is the only one that has performance issues as I can compare it to the others from the Profiler within Atlas. The collection itself has 680k documents and we are using Mongoose within our node.js app.I am wondering if there are any best practices for optimizing the countDocuments() operation?Here is the the log document from the Profiler:
Code:Models.Pass.countDocuments({ show: showId }).maxTimeMS(17000)
{
 "command": {
   "aggregate": "passes",
   "pipeline": [
     {
       "$match": {
         "show": {
           "$oid": "5d8021bd1c4eef00086d4fb6"
         }
       }
     },
     {
       "$group": {
         "_id": 1,
         "n": {
           "$sum": 1
         }
       }
     }
   ],
   "cursor": {},
   "lsid": {
     "id": {
       "$uuid": "c54a4dc4-d595-fe6d-16b9-8517594f2da1"
     }
   },
   "$clusterTime": {
     "clusterTime": {
       "$timestamp": {
         "t": 1584299634,
         "i": 255
       }
     },
     "signature": {
       "hash": {
         "$binary": "PHh4eHh4eD4=",
         "$type": 0
       },
       "keyId": 6778896889304580000
     }
   },
   "$db": "main"
 },
 "planSummary": [
   {
     "COUNT_SCAN": {
       "show": 1
     }
   }
 ],
 "numYields": 1836,
 "queryHash": "97FA1A2E",
 "planCacheKey": "D86294E6",
 "ok": 0,
 "errMsg": "Error in $cursor stage :: caused by :: operation was interrupted because a client disconnected",
 "errName": "ClientDisconnect",
 "errCode": 279,
 "reslen": 311,
 "locks": {
   "ReplicationStateTransition": {
     "acquireCount": {
       "w": 1838
     }
   },
   "Global": {
     "acquireCount": {
       "r": 1838
     }
   },
   "Database": {
     "acquireCount": {
       "r": 1837
     }
   },
   "Collection": {
     "acquireCount": {
       "r": 1837
     }
   },
   "Mutex": {
     "acquireCount": {
       "r": 2
     }
   }
 },
 "protocol": "op_msg",
 "millis": 17594
}

[Assistant]
Text:I see that there is an index on the query filter field show. The query planner does show a COUNT_SCAN stage when the index is used. I ran a similar query (including a filter) with over a million small documents. As such you cannot run explain on the countDocuments method in mongo shell. So, I ran an aggregation with $match and $count stages (and I believe its operation is same as countDocuments)., so that I can see the query plan output. This timed approximately 500ms (running on MongoDB 4.2 on an older PC).When an index is not there, the query plan shows a COLLSCAN and the time is about 1000ms.I think the performance might be something to do with the ‘load’ only. Does this operation has different semantics than other read methods like find (I don’t know)?db.collection.find( { some_field: some_criteria } ).count()Note there was an index on the some_filed.
Code:showexplaincountDocuments$match$countfinddb.collection.find( { some_field: some_criteria } ).count()some_filed


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: How to optimize a count query and tags: ['aggregation', 'dot-net', 'indexes']

[User]
Text:Using the c# driver to get a document count, using CountDocumentsAsync is see the following “very slow” command in Atlas profiler:The collection has 760K documents, so I don’t understand keysExamined": 5677198.
The count takes 32 sec, while a find query on the same fields takes under a sec.What can be done to optimize this?MongodB: 3.6.17
C# Driver: 2.10.2
Code:{
  "command": {
    "aggregate": "contacts",
    "pipeline": [
      {
        "$match": {
          "accountId": 158,
          "deleted": null
        }
      },
      {
        "$group": {
          "_id": 1,
          "n": {
            "$sum": 1
          }
        }
      }
    ],
    "cursor": {},
    "$db": "Loopify",
    "lsid": {
      "id": {
        "$uuid": "a84a49c6-c5f5-d6ce-9f33-b8e38d45e1b3"
      }
    },
    "$clusterTime": {
      "clusterTime": {
        "$timestamp": {
          "t": 1583238446,
          "i": 60
        }
      },
      "signature": {
        "hash": {
          "$binary": "PHh4eHh4eD4=",
          "$type": 0
        },
        "keyId": 6748499292626878000
      }
    }
  },
  "planSummary": [
    {
      "IXSCAN": {
        "accountId": 1,
        "deleted": 1,
        "tagGroups.name": 1,
        "tagGroups.tags": 1,
        "firstName": 1,
        "lastName": 1
      }
    }
  ],
  "keysExamined": 5677198,
  "docsExamined": 139458,
  "cursorExhausted": 1,
  "numYields": 44674,
  "nreturned": 1,
  "reslen": 238,
  "locks": {
    "Global": {
      "acquireCount": {
        "r": 89352
      }
    },
    "Database": {
      "acquireCount": {
        "r": 44676
      }
    },
    "Collection": {
      "acquireCount": {
        "r": 44676
      }
    }
  },
  "protocol": "op_msg",
  "millis": 32279
}

[Assistant]
Text:@Erlend_Baerland Welcome to the forum!Can you provide some more details to help investigate this:The executionStats output includes more detail of query processing stages (work performed such as keys & documents examined, ranges for index searches, etc).Thanks,
Stennie
Code:mongoexplain("executionStats")executionStats

[User]
Text:Hi,
We’re using M10 (General) - Replica Set - 3 nodesWith this query:The result is:
Code:db.contacts.explain("executionStats").aggregate(
[
      {
        "$match": {
          "accountId": 158,
          "deleted": null
        }
      },
      {
        "$group": {
          "_id": 1,
          "n": {
            "$sum": 1
          }
        }
      }
    ]
)
{
    "serverInfo" : {
        "host" : "<removed>",
        "port" : 27017.0,
        "version" : "3.6.17",
        "gitVersion" : "3d6953c361213c5bfab23e51ab274ce592edafe6"
    },
    "stages" : [
        {
            "$cursor" : {
                "query" : {
                    "accountId" : 158.0,
                    "deleted" : null
                },
                "queryPlanner" : {
                    "plannerVersion" : 1.0,
                    "namespace" : "Loopify.contacts",
                    "indexFilterSet" : false,
                    "parsedQuery" : {
                        "$and" : [
                            {
                                "accountId" : {
                                    "$eq" : 158.0
                                }
                            },
                            {
                                "deleted" : {
                                    "$eq" : null
                                }
                            }
                        ]
                    },
                    "winningPlan" : {
                        "stage" : "FETCH",
                        "filter" : {
                            "deleted" : {
                                "$eq" : null
                            }
                        },
                        "inputStage" : {
                            "stage" : "IXSCAN",
                            "keyPattern" : {
                                "accountId" : 1.0,
                                "deleted" : 1.0,
                                "tagGroups.name" : 1.0,
                                "tagGroups.tags" : 1.0,
                                "firstName" : 1.0,
                                "lastName" : 1.0
                            },
                            "indexName" : "accountId_1_deleted_1_tagGroups.name_1_tagGroups.tags_1_firstName_1_lastName_1",
                            "isMultiKey" : true,
                            "multiKeyPaths" : {
                                "accountId" : [

                                ],
                                "deleted" : [

                                ],
                                "tagGroups.name" : [
                                    "tagGroups"
                                ],
                                "tagGroups.tags" : [
                                    "tagGroups",
                                    "tagGroups.tags"
                                ],
                                "firstName" : [

                                ],
                                "lastName" : [

                                ]
                            },
                            "isUnique" : false,
                            "isSparse" : false,
                            "isPartial" : false,
                            "indexVersion" : 2.0,
                            "direction" : "forward",
                            "indexBounds" : {
                                "accountId" : [
                                    "[158.0, 158.0]"
                                ],
                                "deleted" : [
                                    "[null, null]"
                                ],
                                "tagGroups.name" : [
                                    "[MinKey, MaxKey]"
                                ],
                                "tagGroups.tags" : [
                                    "[MinKey, MaxKey]"
                                ],
                                "firstName" : [
                                    "[MinKey, MaxKey]"
                                ],
                                "lastName" : [
                                    "[MinKey, MaxKey]"
                                ]
                            }
                        }
                    },
                    "rejectedPlans" : [
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "mobile" : 1.0
                                },
                                "indexName" : "accountId_1_mobile_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "mobile" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "mobile" : [
                                        "[MinKey, MaxKey]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "email" : 1.0
                                },
                                "indexName" : "accountId_1_email_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "email" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "email" : [
                                        "[MinKey, MaxKey]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "_id" : 1.0
                                },
                                "indexName" : "accountId_1__id_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "_id" : [

                                    ]
                                },
                                "isUnique" : true,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "_id" : [
                                        "[MinKey, MaxKey]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0
                                },
                                "indexName" : "accountId_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "deleted" : 1.0,
                                    "firstName" : 1.0,
                                    "lastName" : 1.0
                                },
                                "indexName" : "accountId_1_deleted_1_firstName_1_lastName_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "deleted" : [

                                    ],
                                    "firstName" : [

                                    ],
                                    "lastName" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "deleted" : [
                                        "[null, null]"
                                    ],
                                    "firstName" : [
                                        "[MinKey, MaxKey]"
                                    ],
                                    "lastName" : [
                                        "[MinKey, MaxKey]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "firstName" : 1.0,
                                    "lastName" : 1.0
                                },
                                "indexName" : "accountId_1_firstName_1_lastName_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "firstName" : [

                                    ],
                                    "lastName" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "firstName" : [
                                        "[MinKey, MaxKey]"
                                    ],
                                    "lastName" : [
                                        "[MinKey, MaxKey]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "externalId" : 1.0,
                                    "deleted" : 1.0
                                },
                                "indexName" : "accountId_1_externalId_1_deleted_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "externalId" : [

                                    ],
                                    "deleted" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "externalId" : [
                                        "[MinKey, MaxKey]"
                                    ],
                                    "deleted" : [
                                        "[null, null]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "deleted" : 1.0,
                                    "tagGroups.name" : 1.0,
                                    "tagGroups.tags" : 1.0
                                },
                                "indexName" : "accountId_1_deleted_1_tagGroups.name_1_tagGroups.tags_1",
                                "isMultiKey" : true,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "deleted" : [

                                    ],
                                    "tagGroups.name" : [
                                        "tagGroups"
                                    ],
                                    "tagGroups.tags" : [
                                        "tagGroups",
                                        "tagGroups.tags"
                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "deleted" : [
                                        "[null, null]"
                                    ],
                                    "tagGroups.name" : [
                                        "[MinKey, MaxKey]"
                                    ],
                                    "tagGroups.tags" : [
                                        "[MinKey, MaxKey]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "deleted" : 1.0
                                },
                                "indexName" : "accountId_1_deleted_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "deleted" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "deleted" : [
                                        "[null, null]"
                                    ]
                                }
                            }
                        },
                        {
                            "stage" : "FETCH",
                            "filter" : {
                                "deleted" : {
                                    "$eq" : null
                                }
                            },
                            "inputStage" : {
                                "stage" : "IXSCAN",
                                "keyPattern" : {
                                    "accountId" : 1.0,
                                    "deleted" : 1.0,
                                    "_id" : 1.0,
                                    "firstName" : 1.0,
                                    "lastName" : 1.0
                                },
                                "indexName" : "accountId_1_deleted_1__id_1_firstName_1_lastName_1",
                                "isMultiKey" : false,
                                "multiKeyPaths" : {
                                    "accountId" : [

                                    ],
                                    "deleted" : [

                                    ],
                                    "_id" : [

                                    ],
                                    "firstName" : [

                                    ],
                                    "lastName" : [

                                    ]
                                },
                                "isUnique" : false,
                                "isSparse" : false,
                                "isPartial" : false,
                                "indexVersion" : 2.0,
                                "direction" : "forward",
                                "indexBounds" : {
                                    "accountId" : [
                                        "[158.0, 158.0]"
                                    ],
                                    "deleted" : [
                                        "[null, null]"
                                    ],
                                    "_id" : [
                                        "[MinKey, MaxKey]"
                                    ],
                                    "firstName" : [
                                        "[MinKey, MaxKey]"
                                    ],
                                    "lastName" : [
                                        "[MinKey, MaxKey]"
                                    ]
                                }
                            }
                        }
                    ]
                },
                "executionStats" : {
                    "executionSuccess" : true,
                    "nReturned" : 153151.0,
                    "executionTimeMillis" : 48409.0,
                    "totalKeysExamined" : 6319057.0,
                    "totalDocsExamined" : 153151.0,
                    "executionStages" : {
                        "stage" : "FETCH",
                        "filter" : {
                            "deleted" : {
                                "$eq" : null
                            }
                        },
                        "nReturned" : 153151.0,
                        "executionTimeMillisEstimate" : 46454.0,
                        "works" : 6319058.0,
                        "advanced" : 153151.0,
                        "needTime" : 6165906.0,
                        "needYield" : 0.0,
                        "saveState" : 49917.0,
                        "restoreState" : 49917.0,
                        "isEOF" : 1.0,
                        "invalidates" : 0.0,
                        "docsExamined" : 153151.0,
                        "alreadyHasObj" : 0.0,
                        "inputStage" : {
                            "stage" : "IXSCAN",
                            "nReturned" : 153151.0,
                            "executionTimeMillisEstimate" : 14458.0,
                            "works" : 6319058.0,
                            "advanced" : 153151.0,
                            "needTime" : 6165906.0,
                            "needYield" : 0.0,
                            "saveState" : 49917.0,
                            "restoreState" : 49917.0,
                            "isEOF" : 1.0,
                            "invalidates" : 0.0,
                            "keyPattern" : {
                                "accountId" : 1.0,
                                "deleted" : 1.0,
                                "tagGroups.name" : 1.0,
                                "tagGroups.tags" : 1.0,
                                "firstName" : 1.0,
                                "lastName" : 1.0
                            },
                            "indexName" : "accountId_1_deleted_1_tagGroups.name_1_tagGroups.tags_1_firstName_1_lastName_1",
                            "isMultiKey" : true,
                            "multiKeyPaths" : {
                                "accountId" : [

                                ],
                                "deleted" : [

                                ],
                                "tagGroups.name" : [
                                    "tagGroups"
                                ],
                                "tagGroups.tags" : [
                                    "tagGroups",
                                    "tagGroups.tags"
                                ],
                                "firstName" : [

                                ],
                                "lastName" : [

                                ]
                            },
                            "isUnique" : false,
                            "isSparse" : false,
                            "isPartial" : false,
                            "indexVersion" : 2.0,
                            "direction" : "forward",
                            "indexBounds" : {
                                "accountId" : [
                                    "[158.0, 158.0]"
                                ],
                                "deleted" : [
                                    "[null, null]"
                                ],
                                "tagGroups.name" : [
                                    "[MinKey, MaxKey]"
                                ],
                                "tagGroups.tags" : [
                                    "[MinKey, MaxKey]"
                                ],
                                "firstName" : [
                                    "[MinKey, MaxKey]"
                                ],
                                "lastName" : [
                                    "[MinKey, MaxKey]"
                                ]
                            },
                            "keysExamined" : 6319057.0,
                            "seeks" : 1.0,
                            "dupsTested" : 6319057.0,
                            "dupsDropped" : 6165906.0,
                            "seenInvalidated" : 0.0
                        }
                    }
                }
            }
        },
        {
            "$group" : {
                "_id" : {
                    "$const" : 1.0
                },
                "n" : {
                    "$sum" : {
                        "$const" : 1.0
                    }
                }
            }
        }
    ],
    "ok" : 1.0,
    "operationTime" : Timestamp(1583831635, 28),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1583831635, 28),
        "signature" : {
            "hash" : BinData(0, "higLMSwtyXkmzuObjj6EgAsotPk="),
            "keyId" : 6748499292626878465
        }
    }
}

[User]
Text:I think I’m running into this: https://jira.mongodb.org/browse/SERVER-18861If I remove the null check from the match, I get a COUNT_SCAN and executionTimeMillis is down to 420ms.I need to filter out documents where the “deleted” field has a value, so how can I rewrite this and still get the COUNT_SCAN?I’ve tried:and:… but it’s still not using a covered query
Code:deleted: {$eq:null}
deleted: {$type:10}

[Assistant]
Text:With this modified query the explain output showed no FETCH stage and the query plan has a "stage" : "PROJECTION_COVERED".Note that I created an index : { accountId: 1, deleted: 1 }. I am using MongoDB Enterprise version 4.2.3 on a local PC.The query plan (part of it):
Code:"stage" : "PROJECTION_COVERED"{ accountId: 1, deleted: 1 }db.test.aggregate( [
  {
      $match: { accountId: 12 }
  },
  {
      $group: {
          _id: null,
          n: {
              $sum: {
                  $cond: [ { $eq: [ "$deleted", null ] }, 1, 0 ]
              }
          }
      }
  }
] )
{
        "stages" : [
                {
                        "$cursor" : {
                                "query" : {
                                        "accountId" : 12
                                },
                                "fields" : {
                                        "deleted" : 1,
                                        "_id" : 0
                                },
                                "queryPlanner" : {
                                        "plannerVersion" : 1,
                                        "namespace" : "text.test",
                                        "indexFilterSet" : false,
                                        "parsedQuery" : {
                                                "accountId" : {
                                                        "$eq" : 12
                                                }
                                        },
                                        "queryHash" : "DED4FE97",
                                        "planCacheKey" : "C9C471AD",
                                        "winningPlan" : {
                                                "stage" : "PROJECTION_COVERED",
                                                "transformBy" : {
                                                        "deleted" : 1,
                                                        "_id" : 0
                                                },
                                                "inputStage" : {
                                                        "stage" : "IXSCAN",
                                                        "keyPattern" : {
                                                                "accountId" : 1,
                                                                "deleted" : 1
                                                        },
                                                        "indexName" : "accountId_1_deleted_1",
                                                        "isMultiKey" : false,
                                                        ...
}


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Not able to use $exists in $lookup pipeline and tags: []

[User]
Text:I have the below querydb.orders.aggregate([
{
$lookup:
{
from: “warehouses”,
let: { order_item: “$item”, order_qty: “$ordered” },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ “$stock_item”,  “$$order_item” ] },
{“instock”: { “$exists”: true }},         ---- Tried exists in both ways but nothing is working
and giving syntax error.
{ $exists: [ “$instock”,  true ] }
]
}
}
},
{ $project: { stock_item: 0, _id: 0 } }
],
as: “stockdata”
}
}
])
Could you please let me know how to use exists in pipeline query of lookup
Below is the sample collections datadb.orders.insert([
{ “_id” : 1, “item” : “almonds”, “price” : 12, “ordered” : 2 },
{ “_id” : 2, “item” : “pecans”, “price” : 20, “ordered” : 1 },
{ “_id” : 3, “item” : “cookies”, “price” : 10, “ordered” : 60 }
])db.warehouses.insert([
{ “_id” : 1, “stock_item” : “almonds”, warehouse: “A” },
{ “_id” : 2, “stock_item” : “pecans”, warehouse: “A”, “instock” : 80 },
{ “_id” : 3, “stock_item” : “almonds”, warehouse: “B”},
{ “_id” : 4, “stock_item” : “cookies”, warehouse: “B”, “instock” : 40 },
{ “_id” : 5, “stock_item” : “cookies”, warehouse: “A” }
])Thanks
Code:

[Assistant]
Text:You cannot use $exists within a $expr; only aggregation expressions are allowed. But, you can use something like this:
{ $match: { instock: { $exists: true } }So, your present $match may look like this; a combination of two stages instead of the earlier one stage with $and:Now, the aggregation will run without any errors!
Code:$exists$expr{ $match: { instock: { $exists: true } }$match$and{ $match: { $expr:{ $eq: [ "$stock_item", "$$order_item" ] } } },
{ $match: { instock: { $exists: true } } },

[User]
Text:Thank you for your response. It works for me.
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Mongodb or mongodb+srv and tags: ['golang']

[User]
Text:Hello,There are two prefix can be used when connect to a mongodb, mongodb or mongodb+srv, when I check the source code at mongo-go-driver/connstring.go at master · mongodb/mongo-go-driver · GitHub, I found the code below:here SchemeMongoDBSRV is “mongodb+srv”.based on the code, my understanding is if I deploy the mongodb on other servers than the local machine, i.e. on another docker or physical machine, I should use “mongodb+srv” as prefix when connecting to the db.
am I right?James
Code:	if p.Scheme == SchemeMongoDBSRV {
		parsedHosts, err = p.dnsResolver.ParseHosts(hosts, true)
		if err != nil {
			return err
		}
		connectionArgsFromTXT, err = p.dnsResolver.GetConnectionArgsFromTXT(hosts)
		if err != nil {
			return err
		}

		// SSL is enabled by default for SRV, but can be manually disabled with "ssl=false".
		p.SSL = true
		p.SSLSet = true
	}

[User]
Text:Hello, I am using mongo go driver to replacing the globalsign mgo. I use the same connection string in mgo as in mongo-go-driver. During running the test on local machine and gitlab CI, the connection are ok, all the test passed. But when I deploy my service on pre-production, I got error “unable to authenticate using mechanism “SCRAM-SHA-1”: (AuthenticationFailed) Authentication failed”. what I should check in my code and on the pre-production db?
thanks,James
Code:

[Assistant]
Text:SRV is a way to specify a single hostname that resolves to multiple host names. When using SRV, the driver conducts an SRV lookup to get the actual names of all of the hosts. Also, when using SRV, the driver does lookups for TXT records, which can contain specific URI options to configure the driver. Using the “mongodb+srv” prefix tells the driver that you’ve set up all of the SRV records correctly and the URI you’re giving needs to be resolved before using. If you haven’t set all of this up, you shouldn’t be using that prefix.For the authentication error, I don’t remember anything about mgo’s URI parsing off the top of my head. Can you answer the following:– Divjot
Code:

[User]
Text:Hello Divjot,Thanks for the answer. It looks not only an issue in code, I have to rely on the configuration manager help to check the settings.Best,James
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: How can I use date string in c# driver builder? and tags: ['dot-net']

[User]
Text:in c# driver builder is not working and i want to keep date in string only in json. pls suggest.
{
“ProgressDate” : “2019-01-01”
}
var filter1 = Builders.Filter.Where(w => w[“ProgressDate”]==Convert.ToDateTime(“2019-01-01”));yours sincerley
Code:

[Assistant]
Text:Hi @Rajesh_Yadav,Just to clarify, you have documents in a collection with field ProgressDate that stores value in DateTime, and you would like to query using a string format of date given only yyyy-mm-dd i.e. 2019-01-01 ?If so, you can convert using DateTime.Parse() method. For example:Please note that MongoDB stores time in UTC by default. This is the DateTimeStyles.AssumeUniversal param option is for. If you intend to convert the string date from local time to UTC just replaced with DateTimeStyles.AdjustToUniversal. See more info System.Globalization.If this doesn’t answer your question, please provide the following information so that others can help you better:Regards,
Wan.
Code:ProgressDateDateTimeyyyy-mm-dd2019-01-01var stringDate = "2019-01-01";
DateTime dateFilter = DateTime.Parse(stringDate, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal );
var filterDefinition = Builders<Test>.Filter.Where(t => t.ProgressDate==dateFilter);
DateTimeStyles.AssumeUniversalDateTimeStyles.AdjustToUniversal

[User]
Text:it is not getting the record , that means it is not filltering.
version i have used is 1.10.2
and json i have given u which i have kept in mongodb.
and finlly the quey is also given by me.
result is i must get the json i have entered in mondogdb. in c# var filter1
Code:

[Assistant]
Text:and json i have given u which i have kept in mongodb.If that’s the case, the field value is string you don’t need to call Convert.ToDateTime() and  just use string to query it. i.e.Regards,
Wan.
Code:Convert.ToDateTime()var stringDate = "2019-01-01";
var filterDefinition = Builders<Test>.Filter.Where(t => t.ProgressDate==stringDate);

[User]
Text:this one is also not working
var filter = Builders.Filter.Where(w=> w[“ProgressDate”] <= “2019-01-01”);
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Mongo DB Compass Connection String and tags: []

[User]
Text:Not able to identify the connection string from the tutorial.
Code:

[Assistant]
Text:@Utkarsh_14115, have a look at this thread:
https://www.mongodb.com/community/forums/t/error-while-connecting-to-mongodb-compass/48281/2
Code:

[Assistant]
Text:Hi @Utkarsh_14115,I hope you found @007_jb’s response helpful. Please let us know if you are still having any issue.Thanks,
Shubham Ranjan
Curriculum Services Engineer
Code:

[Assistant]
Text:I don’t see how giving us the answer will help. It is like cheating on a test.
I can use the url to bring up the databases, but I won’t know how to do it again, or for a different instance. Why is there a difference between the course showing a full page of fields to enter and my Compass that only has the one URL field? How would I get a different URL for my own if I wanted to start using it?
Code:

[Assistant]
Text:@Mark_03136, does the question in this thread relate to a lab that counts towards the final score, or is it just a quiz (which doesn’t count towards the final score)?Q: Why is there a difference …?
A: The lectures are referencing a much older version of Compass. @Shubham_Ranjan (the Curriculum Services Engineer for this course) has mentioned that they’ll soon get an upgrade.Q: How would I get a different URL…?
A: You get the connection strings on Atlas (which I believe the lectures cover). On there, you’ll find a Version dropdown for different connection string formats. The version that matches the lecture is 3.4 or earlier.

Code:

[Assistant]
Text:Neither, I just wanted to understand what options to consider when connecting.
Code:

[Assistant]
Text:Hi @Mark_03136,As @007_jb mentioned, the user interface of Compass has changed a lot since the time of recording of the videos. As I can see, you are enrolled in the February, 2020 offering. In the March offerings, we have published the upgraded version of course to reflect some of the recent changes.Regarding the connection string, I hope you found @007_jb response helpful. Acquiring the connection string is pretty much same for mongo shell and Compass. For instance, this is how you can acquire the connection string for Compass for your sandbox cluster.Hope it helps!Please let us know if you still have any questions.Thanks,
Shubham Ranjan
Curriculum Services Engineer
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Cannot insert all documents to the MongoDB cloud cluster: Prematurely reached end of stream and tags: ['java']

[User]
Text:I’m using JDK/JRE version like: 1.8.0_192
When I’m inserting documents to the Mongodb cloud cluster, I’m getting always the issue:I’ve tried different connection strings for older drivers like:mongodb://admin:password@cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&maxIdleTimeMS=40000and without maxIdleTimeMS parameter:
mongodb://admin:password@cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=trueFor newer drivers like:
mongodb+srv://admin:password@cluster0-ox90k.mongodb.net/test?retryWrites=true&w=majorityand like:mongodb+srv://admin:password@cluster0-ox90k.mongodb.net/test?retryWrites=true&w=majority&readPreference=secondary&replicaSet=Cluster0-shard-0&ssl=trueIt is worth noting that I can insert half of the documents, but then this error occurs.And nothing helps here.
Code:1.8.0_192Caused by: com.mongodb.MongoSocketReadException: Prematurely reached end of stream
	at com.mongodb.internal.connection.SocketStream.read(SocketStream.java:112)
	at com.mongodb.internal.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:579)
	at com.mongodb.internal.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:444)
	at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:298)
	at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:258)
	at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
	at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
	at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:103)
	at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:60)
	at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128)
	at com.mongodb.internal.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:50)
	at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:435)
	at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:117)
	at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:102)
	at com.mongodb.internal.connection.DefaultServer.getConnection(DefaultServer.java:90)
	at com.mongodb.internal.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:112)
	at com.mongodb.client.internal.ClientSessionBinding$SessionBindingConnectionSource.getConnection(ClientSessionBinding.java:136)
	at com.mongodb.internal.operation.FindOperation$1.call(FindOperation.java:628)
	at com.mongodb.internal.operation.FindOperation$1.call(FindOperation.java:625)
	at com.mongodb.internal.operation.OperationHelper.withReadConnectionSource(OperationHelper.java:462)
	at com.mongodb.internal.operation.FindOperation.execute(FindOperation.java:625)
	at com.mongodb.internal.operation.FindOperation.execute(FindOperation.java:77)
	at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:190)
	at com.mongodb.client.internal.FindIterableImpl.first(FindIterableImpl.java:189)
	at gui.Controller.cloudData(Controller.java:120)
	at gui.Controller.lambda$pushAction$1(Controller.java:111)
	at java.util.ArrayList.forEach(ArrayList.java:1257)
	at gui.Controller.pushAction(Controller.java:111)
	... 58 more
mongodb://admin:password@cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&maxIdleTimeMS=40000maxIdleTimeMSmongodb://admin:password@cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=truemongodb+srv://admin:password@cluster0-ox90k.mongodb.net/test?retryWrites=true&w=majoritymongodb+srv://admin:password@cluster0-ox90k.mongodb.net/test?retryWrites=true&w=majority&readPreference=secondary&replicaSet=Cluster0-shard-0&ssl=true

[Assistant]
Text:Caused by: com.mongodb.MongoSocketReadException: Prematurely reached end of streamThis looks like SSL connection issue… check whether or not JRE’s SSL keystore is set properly.
Code:

[User]
Text:Thanks for the answer, coderkid. can you a bit elaborate how to check it properly?
I’m not sure, but maybe these limits messages would be helpful here.UPD: I suppose I’ve found, at least, place where is located trustore:And I have inside something like:

тест44441048×352 17.4 KB

Code:trustore

[User]
Text:To clarify a bit:I’ve tried everything what I’ve already mentioned here: How to avoid an exception Prematurely reached end of stream using mongoDB Java driver 3.4+ or 3.6+? (during insertion) - Stack Overflowas you can see my post above.My Network Access looks like:
Network Access988×297 13.4 KB
Also I can’t provide any logs, because:“M0 Free Tier and M2/M5 shared clusters do not provide downloadable logs.”
Code:

[Assistant]
Text:Hi @invzbl3,The fact that you can connect and insert for a period of time, could be an indication that it’s not related to the keystore.Looking at both of these log lines:It seems that you are looping through an iterable from Find(), and within the loop you’re inserting documents. If so, it is possible that each of the loop process is taking too long, that either the find cursor has timeout or the server that the cursor is connected to was disconnected.Could you provide more information about how you’re inserting the documents with a snippet code example ?Regards,
Wan.
Code:Caused by: com.mongodb.MongoSocketReadException: Prematurely reached end of stream
   ....
at com.mongodb.client.internal.FindIterableImpl.first(FindIterableImpl.java:189)
Find()

[User]
Text:Hi, @wan, thanks for the answer. My code looks like:The cause of error stacktrace shows me on line:                .append("country", country)).first();By the same logic, I had this exactly error using code snippet like here:I have so far inserted about 50 documents instead of the 176 that I planned using this snippet.
Code: public void data(MongoCollection<Document> collection, String title, String country) {

        Document found = collection.find(new Document("title", title)
                .append("country", country)).first();

        if (found == null) {
            collection.insertOne(new Document("title", title)
                .append("country", country));
        }
}
                .append("country", country)).first();

[Assistant]
Text:Thanks for the snippet code.
This function is called within a loop right ? Also, are you running this in a concurrent/parallel operations ?at java.util.ArrayList.forEach(ArrayList.java:1257)Could you check in Atlas cluster monitoring views the number of connections and operations displayed around the time you’re getting the error ? See also Monitor a Cluster for information how to view the metrics.I’m suspecting that you could be hitting the shared clusters limitations.Regards,
Wan.
Code:

[User]
Text:at gui.Controller.cloudData(Controller.java:120) at gui.Controller.lambda$pushAction$1(Controller.java:111) at java.util.ArrayList.forEach(ArrayList.java:1257)@wan, yes, you’re right about the loop. To correct a bit, my method of program is named like cloudData not data (as I mentioned earlier in snippet), so stacktrace is correct here.Journal is my custom class of parameters that I’m adding inside list.So I’m declaring firstly instance variable:
private List<Journal> journalList;and then I’m using for each to call this method using getters like:journalList.forEach(journal -> cloudData(journal.getTitle(), journal.getCountry()));I don’t think it’s related to concurrent/parallel operations, because I simply using the same function until all documents from list will be added to MongoDb Tier cluster one by one.My metrics looks like:

   Also I’m getting alert like:
Can you tell me, please, can I somehow control/regulate limit of % connections from connection string or something? I suppose it can be solution here if I add something like connection limiter as parameter, but still can insert everything that I need to cluster.P.s. I’ve tried to increase number of milliseconds for parameter maxIdleTimeMS up to 100000 or 1000000 instead of 40000, but it doesn’t affect the overall situation, the same error appears.
Code:cloudDatadataJournalprivate List<Journal> journalList;for eachjournalList.forEach(journal -> cloudData(journal.getTitle(), journal.getCountry()));100000100000040000

[Assistant]
Text:Can you tell me, please, can I somehow control/regulate limit of % connections from connection string or something?Depending on your use case, there are a number of ways that you could try.You could try to reduce the connection pool limit using maxPoolSize parameter (default is 100).  Alternatively could also change the connections pool limit via ConnectionPoolSettings.Builder().maxSize(int).
If you reduce the number of connection pool, you need to be mindful about the time limit a thread may wait for a connection to become available. The default is 2 minutes see also ConnectionPoolSettings.Builder().maxWaitTime(long, TimeUnit).In addition to the above, try to restructure your code. Instead of inserting a document one by one you could utilise BulkWrites operations. Also, looking at your example method cloudData, where you try to find a document and insert if it doesn’t exist, try performing update upsert operation whenever possible.Depending on your use case, you could also consider upgrading the cluster to a dedicated cluster. See also Free, Shared and Dedicated Cluster Comparison.Regards,
Wan.
Code:maxPoolSizecloudData

[User]
Text:Thanks, for valuable answer, @wan. I’ve changed my code to:It works also fine, but the same issue appears after half of inserted documents.Also I’ve already tried to add maxPoolSize and reduce value to 80 and 50 instead of default 100 in format like:mongodb+srv://admin:password@cluster0-ox90k.mongodb.net/test?retryWrites=true&w=majority&maxPoolSize=80unfortunately to no avail, still here:
Caused by: com.mongodb.MongoSocketReadException: Prematurely reached end of streamProbably yes, the most likely option as I see it’s really to pay for upgrade.P.s. I’ll try to combine maxPoolSize and maxWaitTime, as you mentioned, but not sure if it possible solution for connection string.
Code:public void cloudData(MongoCollection<Document> collection, String title, String country) {
  List<WriteModel<Document>> updates = Collections.singletonList(
                new ReplaceOneModel<>(
                        new Document("title", title) // find part
                                .append("country", country),
                        new Document("title", title) // update part
                                .append("country", country),
                        new ReplaceOptions().upsert(true)
                )
        );
}
maxPoolSize8050100mongodb+srv://admin:password@cluster0-ox90k.mongodb.net/test?retryWrites=true&w=majority&maxPoolSize=80Caused by: com.mongodb.MongoSocketReadException: Prematurely reached end of streammaxPoolSizemaxWaitTime

[User]
Text:Finally solved. I should call mongodb.MongoClient.connect once, not each request. So I’ve restructured my code a bit, to call connection once instead of each time when I insert specific document.Thanks for the help, everyone.
Code:mongodb.MongoClient.connect


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: Where to close db connection? and tags: []

[User]
Text:i’m a beginner of programming
and i want to make a discord-bot which use mongo db in kotlinin my reference, the author always close the db connection
but i have no idea where to close connection.is it necessary to close the db connection?( i’m not good at english, so if i made a mistake, feel free to correct me)
Code:

[Assistant]
Text:Hey @1118Just wanted to share some stackover flows related to your question.I am using Mongoose as an ORM for my communication with Mongodb Atlas. And I do not close the connection anywhere. I just open a connection in the node express server, and monitor the connection for disconnection/reconnects
Code:

[Assistant]
Text:The Kotlin application uses a MongoDB Java driver to access the database server. This is a link to a Kotlin program where the code shows the closing of the MongoClient object: How to Insert a MongoDB Document using Kotlin.In general, it is always a good practice to close the resources after they are used and before exiting the application. The MongoClient#close() method API documentation says:Close the client, which will close all underlying cached resources, including, for example, sockets and background monitoring threads.Here is another example:  Connect to MongoDB from Kotlin Application – Example
Code:MongoClient

[User]
Text:@Natac13 @Prasad_Saya
Thank you for the reply.
hmm…, so i should close the connection or not?
Code:

[Assistant]
Text:i should close the connection or not?When you create a MongoClient instance you create a connection; actually a pool of connections (aka connection pool). By default, the pool has 100 connections (and this depends upon the driver). This is configurable within the Java code. This means, ideally, you should have one Mongo Client instance per JVM.So, the application’s client uses a connection from the pool and returns it back to the connection pool after its usage. There is no need for closing the connection explicitly. This way the application avoids creating and closing connections (which is an expensive operation).Of course, you should close the MongoClient instance, with the close() method (I had mentioned in my previous reply) at the closing of the application, to clear all the resources.
Code:MongoClientMongoClientclose()

[Assistant]
Text:Of course, you should close the MongoClient instance, with the close() method (I had mentioned in my previous reply) at the closing of the application, to clear all the resources.This note is about using the code for creating the MongoClient object and its close() method.MongoClient extends an interface called as java.lang.AutoCloseable. When the object implementing this interface is used within a try-with-resources statement (as in code sample below) the object’s close() method is called automatically at the exit of the try block (releasing the associated resources).A feature of using this try-with-resources statement is that, even when the code within the try block aborts abruptly (due to an exception), the close method is called automatically, and safely releasing the associated resources.
Code:MongoClientclose()MongoClientclose()MongoClientjava.lang.AutoCloseabletry-with-resourcesclose()trytry-with-resourcestryclosetry (MongoClient mongoClient = MongoClients.create("mongodb://localhost/")) {
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection<Document> coll = database.getCollection("testColl");
    Document doc = coll.find(new Document()).first();
    System.out.println(doc.toJson());
}


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: How to search in case insensitive way through C# and tags: ['dot-net']

[User]
Text:Hi,I am using following code:Yours sincerely
Code:var client = new MongoClient("mongodb+srv://user:password@cluster.mongodb.net");
var database = client.GetDatabase("PTITSCurve");

var collection = database.GetCollection<BsonDocument>("PlanningData");

var filter = Builders<BsonDocument>.Filter.Eq("WSID", WSId);
var projection = Builders<BsonDocument>.Projection.Exclude("_id");
 System.Collections.Generic.IEnumerable<MongoDB.Bson.BsonDocument> bsonResult = collection.Find<BsonDocument>(filter).Project(projection).ToList();

[Assistant]
Text:I think you might find the following useful.
Code:

[User]
Text:can it be done with out making index, because i want to search fillter on other cols and with out indexs.
even i am ready to change the collation.yours sincerley
Code:

[Assistant]
Text:The concept of collation https://docs.mongodb.com/manual/reference/collation/ will help you.
Code:

[User]
Text:sorry the db is sombodys , he is not allowing to change the collation , so if i can set some thing in connection string or with out collation , then it would be help full, pls give example i am new and do not have time as i have to delever.
Code:


[System] You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB.

[System] The following conversation has title: How to use Binary values in MongoDB Compass? and tags: ['compass']

[User]
Text:Is there a way to use Binary values in queries in MongoDB Compass? I tried different syntaxes, but none of them work. I use the Binary type quite a lot, e.g. for user IDs and it would be really useful if I could build and analyse queries in MongoDB Compass.One syntax that doesn’t give me an error, but produces no results is like this: { "user_id": Binary('AjHO4fVjpb6GOvVhHeHOQ==', 0) }
Code:BinaryBinary{ "user_id": Binary('AjHO4fVjpb6GOvVhHeHOQ==', 0) }