diff --git "a/mongoDB_data_hot.jsonl" "b/mongoDB_data_hot.jsonl" new file mode 100644--- /dev/null +++ "b/mongoDB_data_hot.jsonl" @@ -0,0 +1,892 @@ +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Aggregate $match _id $eq $toObjectId not working and tags: ['aggregation', 'compass']"}, {"role": "user", "content": "Text:Using Compass 1.30.1, I was testing an aggregation and getting unexpected results. A $match was not working as expected. The simplified aggregation is:And this gives the expected result by finding a document:try to get the same document by _id:does not find a document. Why does the second $match not find a document?\nCode:db.getCollection('dlsComponents').aggregate([\n { $match: { library: 'Library1', collection: 'Collection1', media: 'Images', object: 'Image3' } }\n ])\n{ _id: ObjectId(\"61fc458b46d7874a3a97ef79\"),\n library: 'Library1',\n collection: 'Collection1',\n media: 'Images',\n object: 'Image3',\n info: 'Image: 1/1/Images/Image3 Info', \u2026\ndb.getCollection('dlsComponents').aggregate([\n { $match: { _id: { $eq: { $toObjectId: \"61fc458b46d7874a3a97ef79\" } } } }\n ])\n"}, {"role": "user", "content": "Text:I found that:{ $match: { $expr: { $eq: [ \u2018$_id\u2019, \u2018$$imageId\u2019 ] } } }does work ($$imageId is an ObjectId used in the non-simplified aggregate). Maybe the { $eq: \u2018$value\u2019 } format does not work in pipelines.\nCode:"}, {"role": "assistant", "content": "Text:Hi David,The $eq used in find()/$match (without $expr) must specify an exact value: https://docs.mongodb.com/manual/reference/operator/query/eq/You can use $eq: ObjectId(\"...\")Jess\nCode:$eq$eq: ObjectId(\"...\")"}, {"role": "assistant", "content": "Text:Your last post made me think that may be $toObjectId works only inside $expr. I triedand it works.\nCode:{ $match: { $expr : { $eq: [ '$_id' , { $toObjectId: \"61fc458b46d7874a3a97ef79\" } ] } } }\n"}, {"role": "assistant", "content": "Text:See on a related topicand\nCode:"}, {"role": "assistant", "content": "Text:even gpt4 doesn\u2019t solve my problem, thank\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Unable to look up TXT record for host ****.****.mongodb.net from GCP ap and tags: ['java', 'atlas-cluster', 'spring-data-odm']"}, {"role": "user", "content": "Text:I have a single node GCP cluster with my spring-boot app running. I recently created a new DB [M10] cloud atlas and trying to connect it via my app. However, I keep getting the following error - screenshot attached\n\nScreenshot 2022-06-11 at 14.27.531920\u00d7961 289 KB\nHowever, I am able to connect to my old DBs [M20 and M10] via the same GCP cluster and same spring-boot app.I am unable to figure out what could be the reason? Any idea?Thanks in advance\nPranav\nCode:"}, {"role": "assistant", "content": "Text:Is there a final \u201cCaused by\u201d that\u2019s cut off from that screen shot? That could help diagnose the issue. It\u2019s possible that you\u2019re running into https://jira.mongodb.org/browse/JAVA-4018, in which case updating the Java driver to 4.5.1 or later will fix it.Is this a self-managed cluster, or are using Atlas, or some other service? I am pretty sure that Atlas always registers a TXT record in DNS, but other services may not.\nCode:"}, {"role": "user", "content": "Text:final caused by :\n\nScreenshot 2022-06-11 at 22.39.332870\u00d71014 414 KB\nI am using Atlas and spring-boot-starter-data-mongodb 4.6.0the other 2 DBs are also from Atlas and I am able to connect to them\nCode:"}, {"role": "user", "content": "Text:from the bug you referenced it looks like it may have re-appeared in 4.6.0.\nCode:"}, {"role": "user", "content": "Text:4.6.0sorry i am using spring-boot-starter-data-mongodb 4.7.0 which internally uses 4.6.0 mongo java driver\nCode:"}, {"role": "assistant", "content": "Text:You can see from the stack trace that it\u2019s using mongodb-driver-core-4.4.0.jar.\nCode:"}, {"role": "user", "content": "Text:Thanks for spotting that. But after upgrading I am still getting DNS issues\nScreenshot 2022-06-12 at 16.26.112672\u00d7864 316 KB\n\nCode:"}, {"role": "assistant", "content": "Text:It is not the same address as before.\nCode:"}, {"role": "user", "content": "Text:yeah\u2026 i deleted the previous DB and created new one\nCode:"}, {"role": "user", "content": "Text:any idea what might be wrong? I am using the same old username/pass combination that I have for the other 2 DB [no special character] . didn\u2019t find anything relevant online\nCode:"}, {"role": "user", "content": "Text:There\u2019s something wrong with the new Atlas DB instances. There seems to be an issue only while connecting with the new DB. The old DB connection are working perfectly fine\nCode:"}, {"role": "assistant", "content": "Text:Notice that now the TXT record is no longer failing (that happens first) but SRV lookup is still failing. Using dig, I\u2019m able to resolve both TXT and SRV records for this host:Can you try the same from the same server on which you\u2019re running the Java application?\nCode:~$ dig SRV _mongodb._tcp.hk-prod.h8dkbpg.mongodb.net\n\n; <<>> DiG 9.10.6 <<>> SRV _mongodb._tcp.hk-prod.h8dkbpg.mongodb.net\n;; global options: +cmd\n;; Got answer:\n;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19870\n;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 1\n\n;; OPT PSEUDOSECTION:\n; EDNS: version: 0, flags:; udp: 512\n;; QUESTION SECTION:\n;_mongodb._tcp.hk-prod.h8dkbpg.mongodb.net. IN SRV\n\n;; ANSWER SECTION:\n_mongodb._tcp.hk-prod.h8dkbpg.mongodb.net. 60 IN SRV 0 0 27017 ac-gokumri-shard-00-00.h8dkbpg.mongodb.net.\n_mongodb._tcp.hk-prod.h8dkbpg.mongodb.net. 60 IN SRV 0 0 27017 ac-gokumri-shard-00-01.h8dkbpg.mongodb.net.\n_mongodb._tcp.hk-prod.h8dkbpg.mongodb.net. 60 IN SRV 0 0 27017 ac-gokumri-shard-00-02.h8dkbpg.mongodb.net.\n\n;; Query time: 167 msec\n;; SERVER: 127.0.0.1#53(127.0.0.1)\n;; WHEN: Sun Jun 12 12:08:08 EDT 2022\n;; MSG SIZE rcvd: 256\n\n~$ dig TXT _mongodb._tcp.hk-prod.h8dkbpg.mongodb.net\n\n; <<>> DiG 9.10.6 <<>> TXT _mongodb._tcp.hk-prod.h8dkbpg.mongodb.net\n;; global options: +cmd\n;; Got answer:\n;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 7702\n;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1\n\n;; OPT PSEUDOSECTION:\n; EDNS: version: 0, flags:; udp: 512\n;; QUESTION SECTION:\n;_mongodb._tcp.hk-prod.h8dkbpg.mongodb.net. IN TXT\n\n;; ANSWER SECTION:\n_mongodb._tcp.hk-prod.h8dkbpg.mongodb.net. 60 IN TXT \"authSource=admin&replicaSet=atlas-tbk5qg-shard-0\"\n\n;; Query time: 35 msec\n;; SERVER: 127.0.0.1#53(127.0.0.1)\n;; WHEN: Sun Jun 12 12:08:57 EDT 2022\n;; MSG SIZE rcvd: 131\n\n"}, {"role": "user", "content": "Text:looks like dig worked.\n\nScreenshot 2022-06-12 at 18.45.311752\u00d71494 139 KB\nthen maybe some issue with com.mongodb.internal.dns.DefaultDnsResolver ?\nCode:"}, {"role": "assistant", "content": "Text:I think it is something in your environment. I am able to connect successfully to your cluster from both the mongo shell and a Java application.\nCode:"}, {"role": "user", "content": "Text:If the issue was with the environment wouldn\u2019t there be an issue connecting to other Atlas DB? [as mentioned previously, I am able to connect to the other 2 DB via the same GCP server, same application]\nCode:"}, {"role": "assistant", "content": "Text:Not necessarily, but I don\u2019t have a hypothesis that explains what both of us are seeing. I think at this point you should open a support ticket (https://www.mongodb.com/docs/manual/support/) to try to get to the root cause.Regards,\nJeff\nCode:"}, {"role": "assistant", "content": "Text:Having the same issue as Pranav. GCP is failing to connect, works on my local environment. GCP works when connecting to older instances of Atlas.\nCode:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appConfig' defined in URL [jar:file:/opt/app/server/app.jar!/BOOT-INF/classes!/com/devnotes/server/app/AppConfig.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.devnotes.server.app.AppConfig]: Constructor threw exception; nested exception is com.mongodb.MongoConfigurationException: Unable to look up TXT record for host dev.7f***.mongodb.net at org.springframework.beans.factory.support.ConstructorResolver.instantiate\n"}, {"role": "assistant", "content": "Text:Nevermind, just started happening in my local environment as well.\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m facing the same issue, but did not find any solution on the forum here which works.\nI can connect to a DB on cluster0.dnqegeu.mongodb.net or cluster0.xfzokj5.mongodb.net with the MongoDB Compass application,\nBUT my java spring application fails to connect to a URI with mongodb+srv://\nWhile the mongodb driver should use the SRV entries of the DNS, it looks for a TXT entry.\nThe library in use is mongodb-driver-core-4.8.2.jar\nAny suggestion please?\nCode:cluster0.dnqegeu.mongodb.netcluster0.xfzokj5.mongodb.netmongodb+srv://mongodb-driver-core-4.8.2.jar"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: (Unauthorized) not authorized on admin to execute command and tags: ['node-js']"}, {"role": "user", "content": "Text:I have created free cluster and db on Mongo Atlas but I try to connect my app by mongoose.connect(\u2018mongodb+srv://Ahmed:Admin123@st.0qt0i.mongodb.net/bktrans?retryWrites=true&w=majority\u2019)And the below error appears when I run rpm start on my API:(Unauthorized)not authorized on admin to execute command {listIndexes: \u201cconsumers\u201c, cursor:{ }, $clusterTime: { clusterTime: {1634734692 10}, signature: { hash: {203 165 207 4 203 170 4 127 37 213 33 4 100 167 170 44 201 49 111 36} }} } \u2026\nCode:"}, {"role": "assistant", "content": "Text:Hi Ahmed ,I got this error recently while connecting from a node app on Heroku to MongoDB Atlas - I had issue with connection string .I tried using below the below format - and it worked.mongodb://:@-cluster0-shard-00-00.scxjr.mongodb.net:27017,-cluster0-shard-00-01.scxjr.mongodb.net:27017,-cluster0-shard-00-02.scxjr.mongodb.net:27017/?ssl=true&replicaSet=atlas--shard-0&authSource=admin&retryWrites=true&w=majorityIt worked.I got this from MongoDB Atlas tab \u2192 Deployment side bar \u2192 Databases \u2192 on right Connect button inside . Connect to your application section \u2192 Select Driver - Node.js and Version 2.2.12 or later - below it will show the example connection string.Please let me know if this solved your issue\nCode:"}, {"role": "assistant", "content": "Text:God bless you. *Tears of joy :_ ))\nCode:"}, {"role": "assistant", "content": "Text:hello, I am getting same kind of error like:\n(Unauthorized) not authorized on admin to execute command { create: \u201csample\u201d, capped: true, size: 5242880, writeConcern: { w: \u201cmajority\u201d }, lsid: { id: {4 [133 92 127 66 175 140 79 35 174 118 57 40 59 137 39 110]} }, $clusterTime: { clusterTime: {1678037479 5}, signature: { hash: {0 [235 83 26 247 241 208 26 217 203 154 205 184 108 184 228 33 93 229 204 81]}, keyId: 7153350679543676928.000000 } }, $db: \u201cadmin\u201d }i tried multi[ple ways for creating collection in db. This error i got is when i got connected to mongodb compass and tried to build a connection in db.\nThere are 3 radio buttons available with that, but cant choose which one to choose.\nPlease help me out.\nCode:"}, {"role": "assistant", "content": "Text:I think you are trying to create your collection in admin db\nConnect to test db and try\nAlso share your compass connect string after hiding sensitive information like password,cluster address\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Connect mongod exiting with code 1, can not see specific any error in log file and tags: []"}, {"role": "user", "content": "Text:Very sorry for my short question but I don\u2019t know how to describe my problem. Here is info when I try to run mongo shell:And here are some logs:\nCode: MongoDB shell version v5.0.3\n connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb\n Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :\n connect@src/mongo/shell/mongo.js:372:17\n @(connect):2:6\n exception: connect failed\n exiting with code 1\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":23017, \"ctx\":\"listener\",\"msg\":\"removing socket file\",\"attr\":{\"path\":\"/tmp/mongodb-27017.sock\"}}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4784905, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the global connection pool\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784906, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the FlowControlTicketholder\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":20520, \"ctx\":\"SignalHandler\",\"msg\":\"Stopping further Flow Control ticket acquisitions.\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784908, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the PeriodicThreadToAbortExpiredTransactions\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784909, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the ReplicationCoordinator\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":4784910, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the ShardingInitializationMongoD\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784911, \"ctx\":\"SignalHandler\",\"msg\":\"Enqueuing the ReplicationStateTransitionLock for shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4784912, \"ctx\":\"SignalHandler\",\"msg\":\"Killing all operations for shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4695300, \"ctx\":\"SignalHandler\",\"msg\":\"Interrupted all currently running operations\",\"attr\":{\"opsKilled\":3}}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"TENANT_M\", \"id\":5093807, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down all TenantMigrationAccessBlockers on global shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.249+07:00\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784913, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down all open transactions\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784914, \"ctx\":\"SignalHandler\",\"msg\":\"Acquiring the ReplicationStateTransitionLock for shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":4784915, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the IndexBuildsCoordinator\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784916, \"ctx\":\"SignalHandler\",\"msg\":\"Reacquiring the ReplicationStateTransitionLock for shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784917, \"ctx\":\"SignalHandler\",\"msg\":\"Attempting to mark clean shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4784918, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the ReplicaSetMonitor\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":4784921, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the MigrationUtilExecutor\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"ASIO\", \"id\":22582, \"ctx\":\"MigrationUtil-TaskExecutor\",\"msg\":\"Killing all outstanding egress activity.\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784923, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the ServiceEntryPoint\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784925, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down free monitoring\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20609, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down free monitoring\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784927, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the HealthLog\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784928, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the TTL monitor\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":3684100, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down TTL collection monitor thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":3684101, \"ctx\":\"SignalHandler\",\"msg\":\"Finished shutting down TTL collection monitor thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784929, \"ctx\":\"SignalHandler\",\"msg\":\"Acquiring the global lock for shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784930, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down the storage engine\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22320, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down journal flusher thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22321, \"ctx\":\"SignalHandler\",\"msg\":\"Finished shutting down journal flusher thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.250+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22322, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down checkpoint thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.251+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22323, \"ctx\":\"SignalHandler\",\"msg\":\"Finished shutting down checkpoint thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.251+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20282, \"ctx\":\"SignalHandler\",\"msg\":\"Deregistering all the collections\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.251+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22261, \"ctx\":\"SignalHandler\",\"msg\":\"Timestamp monitor shutting down\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.251+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22317, \"ctx\":\"SignalHandler\",\"msg\":\"WiredTigerKVEngine shutting down\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.251+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22318, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down session sweeper thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.251+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22319, \"ctx\":\"SignalHandler\",\"msg\":\"Finished shutting down session sweeper thread\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.251+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4795902, \"ctx\":\"SignalHandler\",\"msg\":\"Closing WiredTiger\",\"attr\":{\"closeConfig\":\"leak_memory=true,\"}}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.252+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22430, \"ctx\":\"SignalHandler\",\"msg\":\"WiredTiger message\",\"attr\":{\"message\":\"[1634722334:252129][142289:0x7f6df9745700], close_ckpt: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 18, snapshot max: 18 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 7\"}}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.274+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4795901, \"ctx\":\"SignalHandler\",\"msg\":\"WiredTiger closed\",\"attr\":{\"durationMillis\":23}}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.274+07:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22279, \"ctx\":\"SignalHandler\",\"msg\":\"shutdown: removing fs lock...\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.274+07:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4784931, \"ctx\":\"SignalHandler\",\"msg\":\"Dropping the scope cache for shutdown\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.274+07:00\"},\"s\":\"I\", \"c\":\"FTDC\", \"id\":4784926, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down full-time data capture\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.274+07:00\"},\"s\":\"I\", \"c\":\"FTDC\", \"id\":20626, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down full-time diagnostic data capture\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.279+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20565, \"ctx\":\"SignalHandler\",\"msg\":\"Now exiting\"}\n {\"t\":{\"$date\":\"2021-10-20T16:32:14.279+07:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23138, \"ctx\":\"SignalHandler\",\"msg\":\"Shutting down\",\"attr\":{\"exitCode\":0}}\n"}, {"role": "user", "content": "Text:but when I run sudo mongod -f /etc/mongod.conf, I can connect to mongo shell\nCode:"}, {"role": "assistant", "content": "Text:Hi @MAY_CHEAPER,Were you able to find a solution to your issue? Your log snippet starts after shutdown has initiated, so I think the most interesting log lines are missing.If sudo mongod works fine, my first guess would be that there are problems with file & directory permissions that are ignored when you use sudo to start the mongod process as the root user.If so, I recommend fixing file & directory permissions so your mongod process can run as an unprivileged user.Regards,\nStennie\nCode:sudo mongodsudomongodmongod"}, {"role": "user", "content": "Text:I dont know what reason is but after many search on google, I reinstall MongoDB and it works fine. Thanks for your support.\nCode:"}, {"role": "assistant", "content": "Text:@Stennie_X I have the same issue when I am logged in as root to my system and then installing mongodb wondering why will I have permission issues ? and how do i give permission if at all to resolve this ? after i exec to my pod\nCode:"}, {"role": "assistant", "content": "Text:Hello friends\nI have the same problem and I have been searching for about 2 days and I did not get any result and my problem is not solved. Please help me to solve my problem.\nThe error that is displayed for me:i use Centos 7.6 with cpanel,litespeed,cloudlinuxI also checked the port, but it doesn\u2019t show anything:and the /etc/mongod.conf file is as follows:\nCode:[root@srv ~]# mongo\nMongoDB shell version v5.0.15\nconnecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb\nError: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :\nconnect@src/mongo/shell/mongo.js:372:17\n@(connect):2:6\nexception: connect failed\nexiting with code 1\n[root@srv ~]# netstat -an | grep 27017\n[root@srv ~]#\nation: file\n logAppend: true\n path: /var/log/mongodb/mongod.log\n\n# Where and how to store data.\nstorage:\n dbPath: /var/lib/mongo\n journal:\n enabled: true\n# engine:\n# wiredTiger:\n\n# how the process runs\nprocessManagement:\n fork: true # fork and run in background\n pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile\n timeZoneInfo: /usr/share/zoneinfo\n\n# network interfaces\nnet:\n port: 27017\n bindIp: 127.0.0.1, # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.\n\n\nsecurity:\n#authorization: enabled\n\n#operationProfiling:\n\n#replication:\n\n#sharding:\n\n## Enterprise-Only Options\n\n#auditLog:\n"}, {"role": "assistant", "content": "Text:Your mongod should be up & running for you to connect to it\nIf you installed it as service need to start the service first\nIf not installed as service you need to start your mongod manually from command line with appropriate parameters\nCode:"}, {"role": "assistant", "content": "Text:The Mongo service is installed but does not start:and status:pleas help me.\nCode:[root@srv ~]# sudo service mongodb start\nRedirecting to /bin/systemctl start mongodb.service\nFailed to start mongodb.service: Unit not found.\n[root@srv ~]# service mongod status\nRedirecting to /bin/systemctl status mongod.service\n\u25cf mongod.service - MongoDB Database Server\n Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)\n Active: failed (Result: exit-code) since Mon 2023-02-27 16:57:53 +0330; 2h 20min ago\n Docs: https://docs.mongodb.org/manual\n Main PID: 1047495 (code=exited, status=2)\n\nFeb 27 16:57:53 srv.sayansite.com systemd[1]: Started MongoDB Database Server.\nFeb 27 16:57:53 srv.sayansite.com systemd[1]: mongod.service: main process exited, code=exited, status=2/INVALIDARGUMENT\nFeb 27 16:57:53 srv.sayansite.com systemd[1]: Unit mongod.service entered failed state.\nFeb 27 16:57:53 srv.sayansite.com systemd[1]: mongod.service failed.\n"}, {"role": "assistant", "content": "Text:What is funny is that you use the correct name forservice mongod statusbut the wrong one tosudo service mongodb start\nCode:service mongod statussudo service mongodb start"}, {"role": "assistant", "content": "Text:sudo service mongodb startYou are right, but it will be redirected to service mongod start.\nCode:sudo service mongodb start"}, {"role": "assistant", "content": "Text:it will be redirected to service mongod start.To mongodb.service perhaps as indicated by the warning:Redirecting to /bin/systemctl start mongodb.servicewhich is still wrong, otherwise you would not get an error message that saysFailed to start mongodb.service: Unit not found.As mentioned, you are using the correct name, that is mongod when you are querying the status but the wrong name, that is mongodb when you try to start the service.\nCode:Redirecting to /bin/systemctl start mongodb.serviceFailed to start mongodb.service: Unit not found."}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector and tags: ['java', 'connecting', 'spring-data-odm']"}, {"role": "user", "content": "Text:I am getting the following errorusing spring data mongoits a multitenant environment\nchange/create the mongoclient connection per request. Database/user/password change as tenant request.Issue is intermittent and keeps happening randomly.\nCode:Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}.\n\nClient view of cluster state is {type=REPLICA_SET, servers=[\n {address=mongo01:27017, type=UNKNOWN, state=CONNECTING*},\n {address=mongo02:27017, type=REPLICA_SET_SECONDARY, roundTripTime=2.5 ms, state=CONNECTED},\n {address=mongo03:27017, type=REPLICA_SET_SECONDARY, roundTripTime=1.1 ms, state=CONNECTED}\n];\n"}, {"role": "assistant", "content": "Text:Hi @Kushal_Somkuwar,Looking at the logging message - the driver is having trouble connecting to the primary node. The client view of the cluster state shows the state as seen from the Java driver (which spring data uses underneath).Connecting appears to take longer than the 30s timeout to connect to the mongo01 node. So things to check are the server logs - has there been a change in the replicaset topology - eg new primary and secondaries? Also have there been any networking issues between the application and the mongodb nodes?Ross\nCode:mongo01"}, {"role": "user", "content": "Text:Hi @Ross_Lawley ,so application connection with mongodb works fine initially but if the data json is big than it become slow for application and start showing the above error.we have checked the server logs there so no such of connection and I primary node is running fine there is no issue with cluster as well we suspect the same but why would it connect initially if there is a network issue.Kushal\nCode:"}, {"role": "assistant", "content": "Text:Hi @Kushal_Somkuwar,If the driver initially connects then later cannot connect, then that points to some networking issue. It may be intermittent and not happen all the time. But from the drivers perspective it is timing out trying to select a server. The log message just shows you the current view of the servers after selection has failed, which is it is in the process of connecting to the mongo1 node.Ross\nCode:"}, {"role": "user", "content": "Text:Hi @Ross_LawleyI also think the same but we are not getting any exception on mongodb server logs and application just get that error. Is there a way to identify what is exactly is the network issue ?\nCode:"}, {"role": "assistant", "content": "Text:@Kushal_Somkuwar We are facing a similar issue and we are connecting to mongo from Google Cloud.\nDid you find out what was the issue? If so, how did you resolve it?\nCode:"}, {"role": "assistant", "content": "Text:@Ross_Lawley Kindly help. Below is the stack trace\n\u201cNo server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=xxxx, type=UNKNOWN, state=CONNECTING, exception={java.lang.OutOfMemoryError: Java heap space}}, ServerDescription{address=xxx, type=UNKNOWN, state=CONNECTING, exception={java.lang.OutOfMemoryError: Java heap space}}, ServerDescription{address=xxxx, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1401391508, setName=xxx\u2019, canonicalAddress=xxx, hosts=[xxx], passives=[], arbiters=[], primary=xxxx\u2019, tagSet=TagSet{[Tag{name=\u2018nodeType\u2019, value=\u2018ELECTABLE\u2019}, Tag{name=\u2018provider\u2019, value=\u2018GCP\u2019}, Tag{name=\u2018region\u2019, value=\u2018EASTERN_US\u2019}, Tag{name=\u2018workloadType\u2019, value=\u2018OPERATIONAL\u2019}]}, electionId=null, setVersion=6, lastWriteDate=Wed Apr 13 03:33:15 UTC 2022, lastUpdateTimeNanos=6819537012507}]}. Waiting for 30000 ms before timing out\u201d\nCode:"}, {"role": "assistant", "content": "Text:Hi @Sandhya_Kripalani,I noticed this java.lang.OutOfMemoryError: Java heap space in the error message.I\u2019ve never seen that reported before in such a way (as part of the No server chosen exception) but its a sign that your JVM needs more resources.Ross\nCode:java.lang.OutOfMemoryError: Java heap space"}, {"role": "assistant", "content": "Text:@Sandhya_Kripalani you will need to check mongoclient and the number of connections it is making with MongoDB it should be on the higher side. This issue comes when your application keep creating mongoclient object and not closing the existing mongoclient connections. Hope that will help\nCode:"}, {"role": "assistant", "content": "Text:Hello @Ross_Lawley ,I\u2019m having the same issue here, but I use reactive mongodb in a spring boot application.This is my logs messages:And this is my mongodb config:I tried to use different networks to avoid this problem, bit it always gives me the same error.\nCould you help me please?\nCode:org.springframework.data.mongodb.core.ReactiveMongoTemplate - Streaming aggregation: [{ \"$match\" : { \"type\" : { \"$in\" : [\"INACTIVE_SITE\", \"DEVICE_NOT_BILLED\", \"NOT_REPLYING_POLLING\", \"MISSING_KEY_TECH_INFO\", \"MISSING_SITE\", \"ACTIVE_CIRCUITS_INACTIVE_RESOURCES\", \"INCONSISTENT_STATUS_VALUES\", \"TEST_SUPERVISION_RANGE\"]}}}, { \"$project\" : { \"extractionDate\" : 1, \"_id\" : 0}}, { \"$group\" : { \"_id\" : null, \"result\" : { \"$max\" : \"$extractionDate\"}}}, { \"$project\" : { \"_id\" : 0}}] in collection kpi\norg.mongodb.driver.cluster - No server chosen by com.mongodb.reactivestreams.client.internal.ClientSessionHelper$$Lambda$1183/0x000000080129dd60@292878db from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=10.235.79.213:7915, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=10.235.79.89:7915, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out\nluster - No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=10.235.79.213:7915, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=10.235.79.89:7915, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out\ncom.obs.dqsc.interceptor.GlobalExceptionHandler - Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=10.235.79.213:7915, type=UNKNOWN, state=CONNECTING}, {address=10.235.79.89:7915, type=UNKNOWN, state=CONNECTING}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=10.235.79.213:7915, type=UNKNOWN, state=CONNECTING}, {address=10.235.79.89:7915, type=UNKNOWN, state=CONNECTING}]\norg.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolved [org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=10.235.79.213:7915, type=UNKNOWN, state=CONNECTING}, {address=10.235.79.89:7915, type=UNKNOWN, state=CONNECTING}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=10.235.79.213:7915, type=UNKNOWN, state=CONNECTING}, {address=10.235.79.89:7915, type=UNKNOWN, state=CONNECTING}]]\norg.springframework.web.servlet.DispatcherServlet - Completed 500 INTERNAL_SERVER_ERROR\n @Override\n public MongoClient reactiveMongoClient() {\n ConnectionString connectionString = new ConnectionString(\n \"mongodb://\" + username + \":\" + password +\n \"@\" + host1 + \":\" + port\n + \",\" + host2 + \":\" + port +\n \"/?authSource=\" + authSource +\n \"&replicaSet=\" + replica\n );\n\n MongoClientSettings mongoClientSettings = MongoClientSettings.builder()\n .applyToSslSettings(builder ->\n builder.enabled(true).invalidHostNameAllowed(true)\n )\n .applyToConnectionPoolSettings(\n builder -> builder.minSize(10)\n .maxSize(100)\n .maxWaitTime(8,TimeUnit.MINUTES)\n )\n .applyToSocketSettings(builder -> builder.applySettings(SocketSettings.builder().connectTimeout(5,TimeUnit.MINUTES).readTimeout(5,TimeUnit.MINUTES).build()))\n .applyConnectionString(connectionString)\n .build();\n\n return MongoClients.create(mongoClientSettings);\n }\n"}, {"role": "assistant", "content": "Text:Hi Fellow developers,I have recently started seeing this issues again as soon as I switched to ReactMongoTemplate.\nIn my case I am doing multiple find operations as part of flux streams and the connection does not go through after first few subscriptions. It also many times bring the whole cluster down.Please tell me if someone managed to fix this issue.\nCode:"}, {"role": "assistant", "content": "Text:Facing similar issue, any solution?\nCode:"}, {"role": "assistant", "content": "Text:Did you find the root cause as similar issue i am facing.\nCode:"}, {"role": "assistant", "content": "Text:Hi @sunny_tyagi welcome to the community!By \u201csimilar issue\u201d, I assume you see an error message that looks like this:Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}.Is this correct?If yes, then this is a typical timeout error that is shared across all official drivers, where it tries to connect to the primary member of a replica set, and gives up when it cannot find one after 30 seconds (default). See MongoClient settings serverSelectionTimeout.Typically this is caused by network issues where the driver cannot reach the servers. It could be caused by network partition, security settings that prevent the client to reach the server (e.g. IP whitelisting issues), DNS issues, blocked port, among many others.If your app used to be able to connect without issues and now it cannot, then perhaps there is something different now. Things to check may include whether you\u2019re connecting from the same network as before, whether there are DNS changes to the server, whether security settings was changed in the server, or any other network reachability issues that wasn\u2019t there before.If you have checked everything and all seems to be in order, I would suggest you to consult your network administrator to troubleshoot your connectivity issues.Just to be complete, if anyone else is encountering this error in the future, it\u2019s best to create a new topic describing the exact error encountered, along with more specific information such as MongoDB version, driver version, topology description, and the complete error message, since everyone\u2019s situation is different and the same error may be the result of two very different causes Best regards\nKevin\nCode:Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}.serverSelectionTimeout"}, {"role": "assistant", "content": "Text:It was fixed my increasing the socket settings to the approximate time taken for cluster to come up again or reelect a leader. Also increase maxSize to like 10, spring could not handle 100 connections adequately. Now process is a bit slow but still more reliable.\nCode:"}, {"role": "assistant", "content": "Text:could you please add the code snippet ? i am also facing the same issue\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Storing images in MongoDB and tags: ['node-js']"}, {"role": "user", "content": "Text:hello community! i am new to MongoDB, i wanna know if mongodb is good for storing images and how i can store images in mongodb. I am using Node, Express framework and reactjs. Pls i need a perfect tutorial on how i can work with images. Thanks a bunch.\nCode:"}, {"role": "assistant", "content": "Text:Look at https://docs.mongodb.com/manual/core/gridfs/\nCode:"}, {"role": "assistant", "content": "Text:No, MongoDB is not a good place for storing files. If you want to store files, you should use storages like Amazon S3 or Google Could Storage.The good practice is to store the files in a storage and then to just save the URL of the uploaded image in the MongoDB.When it comes to Node.js and Express, I would suggest multer package middleware, which is primarily used for uploading files. If you would use Amazon S3 for a storage, there is also a plug-in multer-s3 package that can be helpful.You can check this video on how to configure Multer and implement image upload on your Node.js server. Once the image is uploaded, Multer will return data to you with destination field included. You can then save that destination in the MongoDB.\nCode:destinationdestination"}, {"role": "user", "content": "Text:i am very grateful. I hope it solves my problem.\nCode:"}, {"role": "assistant", "content": "Text:I had a task last week that required me to upload images to a database. I\u2019ve S3 buckets to store images in the past but I tried MongoDB this time. So, I used a package called express-fileuploader, very similar to Multer, and uploaded my file to a temp directory in the server, from there I grabbed it using the native fs methods and uploaded it to the DB. The image file was uploaded as binary data, ultimately when getting the data you get it as a buffer base 64 if I\u2019m not mistaken. JS can render using different methods.In conclusion, use an S3 bucket or google cloud storage. Uploading to MongoDB is not as complicated as it sounds, but you\u2019ll definitely save some time using other services.\nCode:"}, {"role": "assistant", "content": "Text:Wish people could be much of a use like you\nCode:"}, {"role": "assistant", "content": "Text:can u explain why mongo is not a good place to store files does that include image files ?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: IsConnected not a function in next.js app and tags: ['node-js', 'next-js']"}, {"role": "user", "content": "Text:I\u2019m starting to use the mongodb driver for next.js. I followed the example of How to Integrate MongoDB Into Your Next.js App | MongoDB but first I found that the example code doesn\u2019t work anymore but I manage to make it work with a few tweaks.Now I want to use it in my own app, so I went and npm install mongodb and everything is working, I can query the database and get the results, but the weird thing is the function isConnected is not working. I get a message saying: \u201cTypeError: client.isConnected is not a function\u201d.I\u2019m new with next.js and mongodb, so I don\u2019t get what is happening, in the demo app with the example the function works without problems, but in my app I get this message.Can somebody help me how to make it work? This is the line with the error:const isConnected = await client.isConnected()Thanks everybody.\nCode:"}, {"role": "assistant", "content": "Text:Hey Alejandro -We just pushed a huge update to the next.js repo that changes how a couple of things work, so the issue is def NOT on your end. You\u2019ll just have to make a few minor tweaks.The updated code is here:canary/examples/with-mongodbThe React Framework. Contribute to vercel/next.js development by creating an account on GitHub.But essentially, the way we import the library has changed.Instead of importingand callingTo get our connection to the database. We\u2019ll instead import the library like so:and to access a database in our getServerSideProps, we\u2019ll do:and now the client.isConnected() function should work.The updated library itself looks like this:I would check out the code here for further instructions:\nhttps://github.com/vercel/next.js/blob/canary/examples/with-mongodb/pages/index.jsPlease let me know if that helps! I will update the blog post in the next few days as well to reflect these changes.Thanks!\nCode:import { connectToDatabase } from '../lib/mongodb'\nconst { client } = await connectToDatabase()\nimport clientPromise from '../lib/mongodb'\nconst client = await clientPromise\nclient.isConnected()import { MongoClient } from 'mongodb'\n\nconst uri = process.env.MONGODB_URI\nconst options = {\n useUnifiedTopology: true,\n useNewUrlParser: true,\n}\n\nlet client\nlet clientPromise\n\nif (!process.env.MONGODB_URI) {\n throw new Error('Please add your Mongo URI to .env.local')\n}\n\nif (process.env.NODE_ENV === 'development') {\n // In development mode, use a global variable so that the value\n // is preserved across module reloads caused by HMR (Hot Module Replacement).\n if (!global._mongoClientPromise) {\n client = new MongoClient(uri, options)\n global._mongoClientPromise = client.connect()\n }\n clientPromise = global._mongoClientPromise\n} else {\n // In production mode, it's best to not use a global variable.\n client = new MongoClient(uri, options)\n clientPromise = client.connect()\n}\n\n// Export a module-scoped MongoClient promise. By doing this in a\n// separate module, the client can be shared across functions.\nexport default clientPromise\n"}, {"role": "user", "content": "Text:Thanks for your help Ado, sadly I still get the error that IsConnected is not a function. If I take out the app is connecting and querying the DB without problem.\nCode:"}, {"role": "assistant", "content": "Text:Yes, I have same problem with Alejandro even though I followed exact code as posted. I hope it will be notified by more developers and be fixed soon.\nCode:"}, {"role": "assistant", "content": "Text:In the Next.js example, they used mongodb@^3.5.9.mongo@latest, which is 4.1.1 as of today, does not have isConnected method on MongoClient as far as I see. So if you just installed mongo in your own project, this might be it.\nCode:mongodb@^3.5.9mongo@latest4.1.1isConnectedMongoClient"}, {"role": "assistant", "content": "Text:Well it\u2019s nice to know I\u2019m not the only one having problems with the isConnected not being a function.\nCode:"}, {"role": "user", "content": "Text:thanks and do you know an alternative to this function?\nCode:"}, {"role": "assistant", "content": "Text:to solve the \u201cisConnected is not a function\u201d error, change the function getServerSideProps to:Thanks,\nRafael,\nCode:getServerSidePropsexport async function getServerSideProps(context) {\n\n let isConnected;\n try {\n const client = await clientPromise\n isConnected = true;\n } catch(e) {\n console.log(e);\n isConnected = false;\n }\n\n return {\n props: { isConnected },\n }\n}\n"}, {"role": "assistant", "content": "Text:But how I create /api routing for api calls? I need to create API routes inside /page directory, but it will not accept mongodb.js. Can you share the code of API call, please?\nCode:"}, {"role": "user", "content": "Text:This is how I\u2019m calling my api routes:\nCode:import clientPromise from \"../../../lib/mongodb\";\nexport default async (req, res) => {\n const client = await clientPromise\n const { fieldvalue } = req.query\n const database = client.db('databasename');\n const userdb = await database.collection('collectionname')\n .find({ \"\": `${ fieldvalue }` })\n .project({ \"_id\": 0 })\n .toArray();\n res.json(userdb)\n}"}, {"role": "assistant", "content": "Text:For that problem, the standard solution is to import clientPromise because versions higher than 3.9/4.0 do not have \"import {Mongoclient} \" command.Then also, if you want to use {MongoClient} then,Now it will work\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Error Throwing Unrecognized pipeline stage name: '$search' and tags: []"}, {"role": "user", "content": "Text:I am using MongoDB atlas search.It is always says\u2026below error.Error:Could you help to unblock.\nCode:db.collection.aggregate([{\n$search: {\n\ttext: {\n\t\tquery: 'multi word query',\n\t\tpath: [...some fields],\n\t},\n}}]);\nUncaught exception: Error: command failed: {\n\t\"ok\" : 0,\n\t\"errmsg\" : \"Unrecognized pipeline stage name: '$search'\",\n\t\"code\" : 40324,\n\t\"codeName\" : \"Location40324\"\n} : aggregate failed :\n_getErrorWithCode@src/mongo/shell/utils.js:25:13\ndoassert@src/mongo/shell/assert.js:18:14\n_assertCommandWorked@src/mongo/shell/assert.js:583:17\nassert.commandWorked@src/mongo/shell/assert.js:673:16\nDB.prototype._runAggregate@src/mongo/shell/db.js:266:5\nDBCollection.prototype.aggregate@src/mongo/shell/collection.js:1012:12\nDBCollection.prototype.aggregate@:1:355\n@(shell):1:1\n"}, {"role": "assistant", "content": "Text:Hi @Merlin_Baptista_B,Welcome to MongoDB communityHave you created an atlas search index on that collection?What is the atlas cluster version?It is supported from 4.2+:Get started quickly with Atlas Search by loading sample data to your cluster, creating a search index, and querying your collection.Thanks\nPavel\nCode:"}, {"role": "assistant", "content": "Text:I have the same problem, I have created search index on Atlas cloud via search UI (default search index for now)\nHow can I resolve this issue?\nCode:"}, {"role": "assistant", "content": "Text:Problem solved. I was using local DB instead of the Atlas one\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Unable to connect db because of \"throw new MongoParseError('Invalid scheme, expected connection string to start with \"mongodb://\" or \"mongodb+srv://\"');\" and tags: ['node-js', 'connecting', 'atlas-cluster', 'graphql']"}, {"role": "user", "content": "Text:I am the beginner in programming. Please help me out, dear experienced programmers, if you can.\nNow I am trying to do a simple To-do app. And I want to use there database. I am stuck for already 12 hours on the stage where it is needed to connect database.\nI have the following error after running the command \u201cnode index.js\u201d:I have the next code in index.js:And the file .env:Thank you in advance! \nCode:throw new MongoParseError('Invalid scheme, expected connection string to start with \"mongodb://\" or \"mongodb+srv://\"');\n ^\n\nMongoParseError: Invalid scheme, expected connection string to start with \"mongodb://\" or \"mongodb+srv://\" ...\nconst { ApolloServer, gql } = require(\"apollo-server\");\n\nconst { MongoClient } = require(\"mongodb\");\n\nconst dotenv = require(\"dotenv\");\n\ndotenv.config();\n\nconst { DB_URI, DB_NAME } = process.env;\n\n// A schema is a collection of type definitions (hence \"typeDefs\")\n\n// that together define the \"shape\" of queries that are executed against\n\n// your data.\n\nconst typeDefs = gql`\n\n # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.\n\n # This \"Book\" type defines the queryable fields for every book in our data source.\n\n type Book {\n\n title: String\n\n author: String\n\n }\n\n # The \"Query\" type is special: it lists all of the available queries that\n\n # clients can execute, along with the return type for each. In this\n\n # case, the \"books\" query returns an array of zero or more Books (defined above).\n\n type Query {\n\n books: [Book]\n\n }\n\n`;\n\nconst books = [\n\n {\n\n title: \"The Awakening\",\n\n author: \"Kate Chopin\",\n\n },\n\n {\n\n title: \"City of Glass\",\n\n author: \"Paul Auster\",\n\n },\n\n];\n\n// Resolvers define the technique for fetching the types defined in the\n\n// schema. This resolver retrieves books from the \"books\" array above.\n\nconst resolvers = {\n\n Query: {\n\n books: () => books,\n\n },\n\n};\n\nconst start = async () => {\n\n const client = new MongoClient(DB_URI, {\n\n useNewUrlParser: true,\n\n useUnifiedTopology: true,\n\n });\n\n await client.connect();\n\n const db = client.db(DB_NAME);\n\n // The ApolloServer constructor requires two parameters: your schema\n\n // definition and your set of resolvers.\n\n const server = new ApolloServer({\n\n typeDefs,\n\n resolvers,\n\n csrfPrevention: true,\n\n cache: \"bounded\",\n\n });\n\n // The `listen` method launches a web server.\n\n server.listen().then(({ url }) => {\n\n console.log(`\ud83d\ude80 Server ready at ${url}`);\n\n });\n\n};\n\nstart();\nDB_URI =\n\n \"mongodb+srv://username:password@cluster0.lghcp.mongodb.net/?retryWrites=true&w=majority\";\n\nDB_NAME = Cluster0;\n"}, {"role": "assistant", "content": "Text:Hi @olena_dunamiss welcome to the community!So a big welcome to the coders club! What I gathered so far is that you\u2019re trying to use Apollo GrapQL to connect to a MongoDB database, to create a todo list app. Is this correct?Could you provide some more details:If you\u2019re just starting to code, I would suggest you to learn MongoDB in isolation first (without Apollo or GraphQL) by following MongoDB and Node.js Tutorial - CRUD Operations.Regarding MongoDB + Node, I would also suggest you take a look at the free MongoDB University courses: M001 MongoDB Basics and M220JS MongoDB for JavaScript Developers (although please note that M220JS assumes some familiarity with Javascript/Node).Best regards\nKevin\nCode:DB_URIconsole.log(DB_URI)new MongoClient"}, {"role": "user", "content": "Text:Thank you so much for your response and the materials that you added!\nThe tutorial: Build a GraphQL API with NodeJS and MongoDB (Full-stack MERN Tutorial ) - YouTube\nI added console.log(DB_URI) and I have the following:\nCode:console.log(DB_URI)undefined\nC:\\Users\\Svetl\\test\\node_modules\\mongodb-connection-string-url\\lib\\index.js:9\n return (connectionString.startsWith('mongodb://') ||\n ^\n\nTypeError: Cannot read properties of undefined (reading 'startsWith')``"}, {"role": "assistant", "content": "Text:did you install dotenv package, I almost had same error and I found out I need to install dotenv package so I can access to .env variables dotenv in npm registry\nCode:"}, {"role": "assistant", "content": "Text:I had this same issue and I resolved it by simply removing the \u201c;\u201d at the end of the connection string. So you connection string should just be:That is without the semi-colon at the end.\nCode:\"mongodb+srv://username:password@cluster0.lghcp.mongodb.net/?retryWrites=true&w=majority\"\n"}, {"role": "assistant", "content": "Text:At this moment, I believe I should just quit my job and become a chef\u2026 Thank you, kind sir.\nCode:"}, {"role": "assistant", "content": "Text:Lol\u2026 What are you currently working as btw\u2026 thanks Adam!\nCode:"}, {"role": "assistant", "content": "Text:This was my problem when the mongoose.connect() in my index.js file would not read my process.env. value.Inside my .env file I had the semi-colon at the end as I usually do when writing JavaScript code:\nMONGO_URL=\u201cmongodb+srv:\u2026\u201d;After removing the semi-colons in my .env files thing were finally working in index.js.Thank you for this solution.\nCode:"}, {"role": "assistant", "content": "Text:I don\u2019t know if you are still having this problem, but as one other person said you need to remove the semi-colon ( ; ) from your variables in your .env file. That should make the process.env work properly.\nCode:"}, {"role": "assistant", "content": "Text:WTH!!! Thanks man. Can\u2019t understand coding anymore. 2 full days trying to sort this\u2026\nCode:"}, {"role": "assistant", "content": "Text:Awesome, I removed the ; from end of line of .env and it\u2019s resolved. Thank you;\nCode:"}, {"role": "assistant", "content": "Text:Fantastic, I removed the semicolon at the end of the line .env, and the problem is solved. Thank you;\nCode:"}, {"role": "assistant", "content": "Text:After five long hours of troubleshooting, I see this response. And Guess what happened.\nCode:"}, {"role": "assistant", "content": "Text:After 14 hours of troubleshooting, I finally found the solution to my problem. I was able to find the solution to my problem by searching the documentation for \u201cconnection string\u201d.See - https://www.mongodb.com/docs/atlas/troubleshoot-connection/#special-characters-in-connection-string-password\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: This.options = options ? {}; and tags: ['node-js']"}, {"role": "user", "content": "Text:\nimage1878\u00d71053 160 KB\n\nI run this backend on windows and kali linux worked perfectly but when I tried on ubuntu then it showed an error. could anybody help me?\nCode:"}, {"role": "user", "content": "Text:my code is\n\nimage959\u00d71071 95.7 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Hello @Abu_Said_Shabib, Welcome to the MongoDB community forum,I think you are using mongodb npm\u2019s latest driver version 5, and there are Build and Dependency Changes, Just make sure the below thing,Minimum supported Node version\nThe new minimum supported Node.js version is now 14.20.1\nCode:"}, {"role": "assistant", "content": "Text:Hi, Were you able to find a solution to this problem? I haven\u2019t been lucky so far.\nI have been facing server connection problems due to things (not sure if it\u2019s because of a firewall or vpn or zscaler) but I Started facing this specific problem yesterday after I removed MongoDB from package.json file, deleted package-lock and node-modules and then reinstalled everything, then installed mongo db again.\nI am facing the same error and I haven\u2019t been able to find other questions related to it on the the internet maybe Im looking for the wrong thing in the wrong places.\nplease help.attaching SS of my package.json file.I am using node version 19.8.0\nScreenshot 2023-03-23 at 6.33.00 AM1018\u00d71550 133 KB\n\nCode:"}, {"role": "user", "content": "Text:I can\u2019t solve it but it\u2019s probably problem on Ubuntu network | Firewall | Version or security related issues. Because in other versions of linux it working well. Like I\u2019m tested on kali linux, fedora and zorin os.\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m facing this problem on MacOS Ventura 13.1, my colleague with his MacOS is not facing this issue. I don\u2019t understand what the problem could be.Firewall seems like a probable cause since my colleague has been here longer he must have different access than my laptop (he doesn\u2019t remember, I tried asking him what special permissions his laptop might have).\nCode:"}, {"role": "assistant", "content": "Text:my problem is fixed now,\nit was due to my company\u2019s internet monitoring software blocking the ports I needed to visit. took me a long time to figure it out because the software is newly implemented and the team handling it wasn\u2019t aware that it blocks ports too, not just website.\nCode:"}, {"role": "assistant", "content": "Text:Reciently I find a solution. The comand \u201cnpm i mongoose\u201d today install mongoose version 7.0.1., so I deleted directory \u201cnode_modules\u201d and after I rewrite the file \u201cpackage.json\u201d to replace dependencies as \u201cmongoose\u201d: \u201c^5.1.2\u201d, and ejecute command \u201cnpm i dependences\u201d and node.js will reinstall mongoose in a past version. this works fine for my.\nCode:"}, {"role": "assistant", "content": "Text:Hello @Najib_Shah / @Abu_Said_Shabib / @Ramirez_Gomar_Sergio_JoseWelcome to the MongoDB Community forums As @turivishal mentioned the minimum supported Node.js version is now 14.20.1 for MongoDB Node.js Driver v5. So, please upgrade the node version to 14.20.1 or higher to resolve the issue.The new minimum supported Node.js version is now 14.20.1However, you can refer to my response here where I\u2019ve explained the cause of the this.options = options ?? {}; error.I hope it helps!Regards,\nKushagra\nCode: this.options = options ?? {};"}, {"role": "assistant", "content": "Text:Thank you so much.\nmy problem is resolve due to your solution.\nCode:"}, {"role": "assistant", "content": "Text:3 posts were split to a new topic: Getting Error This.options = options ? {};\nCode:"}, {"role": "assistant", "content": "Text:This worked for me, I downgraded the mongoose version to ^5.1.2 from ^7.5.2\nCode:^5.1.2 ^7.5.2"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MissingSchemaError: Schema hasn't been registered for model UserAddress.address and tags: ['queries', 'node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:Been pulling my hair out for hours now, just can\u2019t figure out why the field refuses to populate. What I want to do is return the AddressId field populated with values instead of just an ID, but nothing I\u2019ve tried works, none of the solutions I found do anything.If you need any other code from the project, I will update the question. Any help is highly appreciated.Order Model:Address Model:Code that runs the query:\nCode:const mongoose = require(\"mongoose\");\n\nconst orderSchema = new mongoose.Schema(\n {\n user: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"User\",\n required: true,\n },\n addressId: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"UserAddress.address\",\n required: true,\n },\n totalAmount: {\n type: Number,\n required: true,\n },\n items: [\n {\n productId: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Product\",\n },\n payablePrice: {\n type: Number,\n required: true,\n },\n purchasedQty: {\n type: Number,\n required: true,\n },\n },\n ],\n paymentStatus: {\n type: String,\n enum: [\"Pending\", \"Completed\", \"Cancelled\", \"Refund\"],\n required: true,\n },\n paymentType: {\n type: String,\n enum: [\"CoD\", \"Card\", \"Wire\"],\n required: true,\n },\n orderStatus: [\n {\n type: {\n type: String,\n enum: [\"Ordered\", \"Packed\", \"Shipped\", \"Delivered\"],\n default: \"Ordered\",\n },\n date: {\n type: Date,\n },\n isCompleted: {\n type: Boolean,\n default: false,\n },\n },\n ],\n },\n { timestamps: true }\n);\n\nmodule.exports = mongoose.model(\"Order\", orderSchema);\nconst mongoose = require(\"mongoose\");\n\nconst addressSchema = new mongoose.Schema({\n name: {\n type: String,\n required: true,\n trim: true,\n min: 10,\n max: 60,\n },\n mobileNumber: {\n type: String,\n required: true,\n trim: true,\n },\n pinCode: {\n type: String,\n required: true,\n trim: true,\n },\n locality: {\n type: String,\n required: true,\n trim: true,\n min: 10,\n max: 100,\n },\n address: {\n type: String,\n required: true,\n trim: true,\n min: 10,\n max: 100,\n },\n cityDistrictTown: {\n type: String,\n required: true,\n trim: true,\n },\n state: {\n type: String,\n required: true,\n required: true,\n },\n landmark: {\n type: String,\n min: 10,\n max: 100,\n },\n alternatePhone: {\n type: String,\n },\n addressType: {\n type: String,\n required: true,\n enum: [\"home\", \"work\"],\n required: true,\n },\n});\n\nconst userAddressSchema = new mongoose.Schema(\n {\n user: {\n type: mongoose.Schema.Types.ObjectId,\n required: true,\n ref: \"User\",\n },\n address: [addressSchema],\n },\n { timestamps: true }\n);\n\nmongoose.model(\"Address\", addressSchema);\nmodule.exports = mongoose.model(\"UserAddress\", userAddressSchema);\nconst Order = require(\"../models/order\");\nconst Cart = require(\"../models/cart\");\nconst Address = require(\"../models/address\");\nconst Product = require(\"../models/product\");\n\nexports.getOrders = (req, res) => {\n Order.find({ user: req.user._id })\n .select(\"_id paymentStatus paymentType orderStatus items addressId\")\n .populate(\"items.productId\", \"_id name productImages\")\n .populate(\"addressId\")\n .exec((error, orders) => {\n if (error) {console.log(error) \n return res.status(400).json({ error });}\n if (orders) {\n res.status(200).json({ orders });\n }\n });\n \n};\n"}, {"role": "assistant", "content": "Text:First, I know nothing about mongoose so what I suggest might be completely wrong.You register addressSchema as the Address model. Everywhere ref: is used, it looks like a model name, rather than the field name of another model.So I would try first to use ref:\"UserAddress.Address\" rather than ref:\"UserAddress.address\", that is the name you use inmongoose.model(\"Address\", addressSchema);rather than the name you use inaddress: [addressSchema]If that fails, I would try ref:\"Address\" because you domongoose.model(\"Address\", addressSchema);You might need to export it like you do for \"UserAddress\".\nCode:ref:\"UserAddress.Address\"ref:\"UserAddress.address\"mongoose.model(\"Address\", addressSchema);address: [addressSchema]ref:\"Address\"mongoose.model(\"Address\", addressSchema);\"UserAddress\""}, {"role": "assistant", "content": "Text:I also got the same error as you. How did you fix it?\nCode:"}, {"role": "assistant", "content": "Text:I got the exact same error,\nmy models were being called correctly everything was correct exceptuserModel.jsorderModel.jsspelling error in the reference. 1 hour wasted on a capital letter left out in the past \nCode:module.exports = mongoose.model( \"user\" , userSchema );\ncustomer: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"User\"\n}\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Recover deleted documents? and tags: ['data-recovery']"}, {"role": "user", "content": "Text:Hi all,I have a collection, where some documents were deleted by accident. Despite having daily backups, this deletion happened before the backups that are available (more than 10 days ago).\nSince the database does not change much or frequently, is it possible these deleted documents are still somewhere in the database files?\nIs there any way to check/find them?\nCode:"}, {"role": "user", "content": "Text:My mongod version is:db version v4.2.8\ngit version: 43d25964249164d76d5e04dd6cf38f6111e21f5f\nOpenSSL version: OpenSSL 1.1.1l FIPS 24 Aug 2021\nallocator: tcmalloc\nmodules: none\nbuild environment:\ndistmod: rhel80\ndistarch: x86_64\ntarget_arch: x86_64\nCode:"}, {"role": "assistant", "content": "Text:Hi @Georgios_Petasis and welcome in the MongoDB Community !If you have a standalone mongod, then no, it\u2019s lost forever.\nIf you have a Replica Set (even a single node), then it means all the write operations are written to the Oplog.The Oplog is a system collection that has a limited size (capped collection) and overwrite the oldest entries as new ones arrive.You can retrieve information about your Oplog with the command:Depending how much write operations are performed on the cluster, the oplog time window can be large or small. It\u2019s a good practice to have a confortable size.If you inserted these documents recently and if you have a large oplog windows, they are still in the oplog.See this little example:With an aggregation pipeline, I can even restore them into the original collection:Cheers,\nMaxime.\nCode:mongod> db.getReplicationInfo()\n{\n logSizeMB: 8423,\n usedMB: 0.01,\n timeDiff: 360,\n timeDiffHours: 0.1,\n tFirst: 'Wed Sep 29 2021 14:35:23 GMT+0000 (Coordinated Universal Time)',\n tLast: 'Wed Sep 29 2021 14:41:23 GMT+0000 (Coordinated Universal Time)',\n now: 'Wed Sep 29 2021 14:41:30 GMT+0000 (Coordinated Universal Time)'\n}\ntest [direct: primary] test> db.coll.insertMany([{name: \"Max\"}, {name: \"Alex\"}, {name: \"Claire\"}])\n{\n acknowledged: true,\n insertedIds: {\n '0': ObjectId(\"61547bd83bbc8bc533a5c784\"),\n '1': ObjectId(\"61547bd83bbc8bc533a5c785\"),\n '2': ObjectId(\"61547bd83bbc8bc533a5c786\")\n }\n}\ntest [direct: primary] test> db.coll.deleteMany({})\n{ acknowledged: true, deletedCount: 3 }\ntest [direct: primary] test> use local\nswitched to db local\ntest [direct: primary] local> db.oplog.rs.find({op: 'i', ns: 'test.coll'}, {o:1})\n[\n { o: { _id: ObjectId(\"61547bd83bbc8bc533a5c784\"), name: 'Max' } },\n { o: { _id: ObjectId(\"61547bd83bbc8bc533a5c785\"), name: 'Alex' } },\n { o: { _id: ObjectId(\"61547bd83bbc8bc533a5c786\"), name: 'Claire' } }\n]\ntest [direct: primary] local> db.oplog.rs.aggregate([{$match: {op: 'i', ns: 'test.coll'}},{$replaceRoot: {newRoot: '$o'}}, { $merge: { into: {db: \"test\", coll: \"coll\"}, on: \"_id\", whenMatched: \"replace\", whenNotMatched: \"insert\" } }])\n\ntest [direct: primary] local> use test \nswitched to db test\ntest [direct: primary] test> db.coll.find()\n[\n { _id: ObjectId(\"61547bd83bbc8bc533a5c784\"), name: 'Max' },\n { _id: ObjectId(\"61547bd83bbc8bc533a5c785\"), name: 'Alex' },\n { _id: ObjectId(\"61547bd83bbc8bc533a5c786\"), name: 'Claire' }\n]\n"}, {"role": "assistant", "content": "Text:Hi Mazime,You solution is very nice i was tested my project in DEV servers it is worked successful.\nbut next i move to my production servers duting recover as you mention steps following\ni need you helpi am waiting you reply\u2026Thanks,\nSrihari\nCode:"}, {"role": "assistant", "content": "Text:The solution I explained above is NOT something you want to use in a production environment on a regular basis. It must be considered as a last resort action when nothing else is suitable (for example a full restore of a daily backup).You can\u2019t trust this solution to work each time because the oplog is a capped collection and old documents will disappear from it eventually.For sharded clusters, you\u2019ll have to apply the same method \u201clocally\u201d on each shard because mongos can\u2019t access the system local database. Each shard has its own oplog completely independent from the other shards.Again, to me, this is an extreme mesure that should never be used. When you remove a document in MongoDB, you should consider that it\u2019s gone for good. If recovering old docs is part of your requirements, I would use another strategy like \u201csoft deletes\u201d (i.e. just set a boolean {deleted:true} and use it to filter with an index).Cheers,\nMaxime.\nCode:local"}, {"role": "assistant", "content": "Text:How to use \u201csoft deletes\u201d (i.e. just set a boolean {deleted:true} and use it to filter with an index). ?can you please brief explain with exampleThanks,\nSrihari\nCode:"}, {"role": "assistant", "content": "Text:I believe what Max is talking about is instead of actually deleting the document(s), you would instead add a field to the document called deleted with a value of true. While this might work in some cases, it could lead to a collection growing to larger sizes. I could however be misunderstanding what he is suggesting.\nCode:deletedtrue"}, {"role": "assistant", "content": "Text:Nope that\u2019s it @Doug_Duncan !Replace delete operation with update $set {deleted:true}.\nAnd find operation should now include something like $exists deleted false to avoid including \u201csoft\u201d deleted documents unless you actually want to access these \u201cdeleted\u201d docs. Then you can find and filter on {deleted:true}.But @Doug_Duncan is also correct that this can lead to collections infinitely growing in size and an additional \u201cdeleted\u201d field in all the indexes to support the queries (so more RAM).Every now and then you will also want to actually delete the docs for real once they have been soft deleted for long enough.For this, I would suggest using a TTL index on another additional field {deletedAt: new Date()} which would be set when the deleted field is set and it would actually delete automatically for real this time the docs after X seconds.There is a trade-off for sure to consider.Cheers,\nMaxime.\nCode:{deleted:true}{deleted:true}{deletedAt: new Date()}deleted"}, {"role": "assistant", "content": "Text:Hi,Do you know if there is anyway to recover document deleted/purged by a TTL index ?\nI had done some testing using oplog, but I couldn\u2019t find any resolution and I don\u2019t think it can be done.\nCan you confirm ?Thanks !\nSally\nCode:"}, {"role": "assistant", "content": "Text:Hi @Yook_20450,Sorry, I\u2019m just reading this now.\nWhen a document is deleted from MongoDB (by a TTL or not), it\u2019s the same result in the oplog. I provided an example in this topic above to explain how a document could be \u201csaved\u201d using the oplog, but it would only work if the oplog is large enough so it still contains the entry that created this doc. If that\u2019s the case, then it will also contain all the following updates that may have occurred to this doc.\nElse it\u2019s lost if you don\u2019t have a backup. Cheers,\nMaxime.\nCode:"}, {"role": "assistant", "content": "Text:Single document was deleted , we need recover that document restore into exited collection.\nWe do not have backupHow to do step by step explain but oplog collection it is placeddb.oplog.rs.find({\u201cns\u201d:\u201cempdb.emptbl\u201d,\u201cop\u201d:\u201cd\u201d,\u201co\u201d:{\u201c_id\u201d :ObjectId(\u201c64ea1ce2b1084f3d73a33001\u201d)}}).sort({$natural:1}).limit(10).pretty()\n{\n\u201cop\u201d : \u201cd\u201d,\n\u201cns\u201d : \u201cempdb.emptbl\u201d,\n\u201cui\u201d : UUID(\u201cc3387486-31b7-4398-9688-9274fd585315\u201d),\n\u201co\u201d : {\n\u201c_id\u201d : ObjectId(\u201c64ea1ce2b1084f3d73a33001\u201d)\n},\n\u201cts\u201d : Timestamp(1696357679, 5),\n\u201ct\u201d : NumberLong(3),\n\u201cv\u201d : NumberLong(2),\n\u201cwall\u201d : ISODate(\u201c2023-10-03T18:27:59.868Z\u201d)\n}\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Copy documents from one collection to another and tags: ['python']"}, {"role": "user", "content": "Text:i have a collection called scheduled_tasks in my db.The collection looks like below:Now,i want to copy the documents in above collection to another collection-say planned_activities.I want to copy only the _id and user field from scheduled_tasks collection to my new collection ie planned_activities.Also in my new collection planned_activities ,apart from _id and user(which i got from scheduled_tasks collection),i want to add two new fields such as old_data and new_data.I want my planned_activities collection to be like belowHow do i achieve this now.I know how to copy from one collection to another,but i am unaware how to achieve it in my case\nCode:{\n \"_id\": {\n \"$oid\": \"6308bbdefcc302677837d855\"\n },\n \"action\": \"xxxxxx\",\n \"user\": \"sandeep\",\n \"scheduled_time\": \"24-08-2022\",\n \"file_path\": \"c://asdhkjshd\",\n \"created_at\": \"22-08-2022\",\n \"updated_at\": \"22-08-2022\"\n}\n\n{\n \"_id\": {\n \"$oid\": \"6308bbdefcc302677837d855\"\n },\n \"action\": \"xxxxxx\",\n \"user\": \"akhil\",\n \"scheduled_time\": \"24-07-2022\",\n \"file_path\": \"c://asdhkjshd\",\n \"created_at\": \"22-07-2022\",\n \"updated_at\": \"22-07-2022\"\n}\n_id:\"6308bbdefcc302677837d855\"\nuser:\"akhil\"\nstatus:null\nold_data:null\nnew_data:2022-08-30T17:58:18.551+00:00\n"}, {"role": "assistant", "content": "Text:You should be able to do this with the aggregation framework. You can $match (if necessary), then $project to get the fields from the current documents you want to use, $addFields to create the new fields and then finally $out to save the new collection.You could also look at $merge which is similar to $out but has more functionality.\nCode:$match$project$addFields$out$merge$out"}, {"role": "assistant", "content": "Text: $project to get the fields from the current documents you want to use, $addFields to create the new fieldsHi @Doug_Duncan,Thanks for sharing a speedy solution!One further improvement: $addFields is equivalent to a $project stage specifying all fields in the input documents. Selection of existing fields and creation of new fields can be done within a $project stage, so an $addFields stage would not be needed for this use case.Regards,\nStennie\nCode:$project$addFields$addFields$project$project$addFields"}, {"role": "assistant", "content": "Text:Selection of existing fields and creation of new fields can be done within a $project stage, so an $addFields stage would not be needed for this use case.Of course you\u2019re right @Stennie_X. Sometimes I don\u2019t stop and think of the solution I propose, and would have compressed those stages into a single one when writing out the query in real time.\nCode:$project$addFields"}, {"role": "user", "content": "Text:Hi @Doug_Duncan and @Stennie_X,\nThanks for the quick reply.\nI have tried the following and it worked:everything looks fine,but I want the order of the fields in the new collection audit_details to be like below:but my new collection looks like below:is there any way to achieve it in the order i require\nCode:scheduled_migration.aggregate([\n {\"$project\": {\"_id\": 1, \"user\": 1, \"status\": \"New\", \"old_migrationtime\": None,\n \"new_migrationtime\": \"$scheduled_time\"}},\n {\"$merge\": {\"into\": \"audit_details\"}}\n_id:\"6308bbdefcc302677837d855\"\nuser:\"akhil\"\nstatus:null\nold_data:null\nnew_data:2022-08-30T17:58:18.551+00:00\n{\n \"_id\": {\n \"$oid\": \"6308bbdefcc302677837d855\"\n },\n \"new_migrationtime\": \"2022-09-26 16:26:00\",\n \"old_migrationtime\": \"2022-07-21 16:26:00\",\n \"status\": \"modified\",\n \"user\": \"xxxxx\",\n \"last_modified\": {\n \"$date\": {\n \"$numberLong\": \"1662039075400\"\n }\n }\n}\n"}, {"role": "assistant", "content": "Text:is there any way to achieve it in the order i requireIf you want your fields in a certain order, then you need to $project those fields in that order. Currently you have: _id, user, status, old_migrationtime, new_migrationtime. Change that to be _id, new_migrationtime, old_migrationtime, status, user.As for the last_modified field, not sure how that got into the documents as it\u2019s not part of the aggregate() call you provided.\nCode:$project_iduserstatusold_migrationtimenew_migrationtime_idnew_migrationtimeold_migrationtimestatususerlast_modifiedaggregate()"}, {"role": "assistant", "content": "Text:Hello,\nCan this be done using insertMany in batches? I am using the below script.\nI thought exporting any collection documents to another collection can be done easily. Could you please advice if I may overlooking something here.var docsToInsert = db.PMForms_local.find({ \u201cexist\u201d: \u201cyes\u201d }).toArray();\nvar batchSize = 20;\nvar successfulInserts = 0;for (var i = 0; i < docsToInsert.length; i += batchSize) {\nvar batch = docsToInsert.slice(i, i + batchSize);\ntry {\nvar result = db.collectionB.insertMany(batch);\nsuccessfulInserts += result.insertedCount;\n} catch (e) {\nprint(\"Error inserting batch starting at index \" + i + \": \" + e.message);\n}\n}\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Conditional $lookup and tags: ['aggregation']"}, {"role": "user", "content": "Text:Is there a way to do a conditional $lookup?I have records in a collection that have an optional (null) field. I\u2019d rather not waste processing on the records for which the lookup field is null. Not to mention that, depending on indexing, doing a $lookup on a null field could still be expensive.\nCode:"}, {"role": "assistant", "content": "Text:With this $lookup syntax,you can specify condition(s) on the join in the pipeline. In your case, that would be a null check condition (in addition to the join conditions).\nCode:{\n $lookup:\n {\n from: ,\n let: { : , \u2026, : },\n pipeline: [ ],\n as: \n }\n}\n"}, {"role": "user", "content": "Text:Yes, the problem with the solution as you posted is this bug:\nhttps://jira.mongodb.org/browse/SERVER-40362So when you get to nulls on a lookup join, the query runs SLOWWWWW. Now, one thing I could do is an ifNull, and then change the null to be a value that I am certain won\u2019t be in in the lookup collection\u2026 but this seems\u2026 jenky. So, was hoping for alternative solution.\nCode:"}, {"role": "assistant", "content": "Text:You can try using a $match before the $lookup, to exclude the documents with the non-existing field:{ $match: { someField: { $exists: true } } }The alternative workaround to use the $ifNull to substitute a null for non-existing field is fine too. Substitute let: { someField : '$someField' } with let: { someField: { $ifNull: [\"$someField\", null ] } }In applications it is not unusual to have unusual cases - data or logic. It just happens this case is a program shortcoming (and temporary only). It is not that bad to have a case by covering with an additional condition, if it helps running the program efficiently. Some documentation around this workaround helps for reference and apply the issue fix later on when available.\nCode:$match$lookup{ $match: { someField: { $exists: true } } }$ifNullnulllet: { someField : '$someField' }let: { someField: { $ifNull: [\"$someField\", null ] } }"}, {"role": "assistant", "content": "Text:Hello. This conditional lookup does not work for me\nMongoDB version: 5\nGUI: robo3t-snap\n\nimage983\u00d7726 69.6 KB\n\nupdatedFieldsByContractor.updatedValues.cities there is not in the original document. it just appears here because of that lookup. I mean when i run this command: db.getCollection('contractors').find({ _id: ObjectId('htat document') }) to get the same document it had not updatedFieldsByContractor.updatedValues.cities field. what should i do to lookup conventionally?\nCode:updatedFieldsByContractor.updatedValues.citiesdb.getCollection('contractors').find({ _id: ObjectId('htat document') })updatedFieldsByContractor.updatedValues.cities"}, {"role": "assistant", "content": "Text:Hello @Kasir_Barati, you cannot refer the contractors collection document fields directly in the $lookup's pipeline $match stage. Please refer the above linked MongoDB documentation for the $lookup and find correct syntax and usage.\nCode:contractors$lookup$match$lookup"}, {"role": "assistant", "content": "Text:@Kasir_Barati, was @Prasad_Saya\u2019s answer help you solve your issue? If it has, please mark the post as the solution.\nCode:"}, {"role": "assistant", "content": "Text:This is not my question. Therefore I cannot select it as the answer\nCode:"}, {"role": "user", "content": "Text:Here I am, a few years later. The original answer is not what I\u2019m looking for. I don\u2019t want to filter out results. I want the entire result set, but only do lookups on certain records.For example, collection fruit and child_fruit. If I do db.child_fruit.aggregate(pipeline), I only want child_fruit records to perform $lookup against fruit collection if child_fruit HAS a value for a field \u201cfruit_name\u201d. For example:##fruit collection\ndb.fruit.insert({name: \u2018Orange\u2019});##child_fruit collection\ndb.child_fruit.insert({name: \u2018Something\u2019, fruit_name: \u2018Orange\u2019});\ndb.child_fruit.insert({name: \u2018Another\u2019});db.child_fruit.aggregate([\n{$lookup: {\nfrom: \u2018fruit\u2019,\n\u2026\n}}\n]);The problem is, given that I still want the \u201cAnother\u201d record back in my final result set, I don\u2019t believe there is a way to \u201cignore\u201d the $lookup for child_fruit records without \u201cfruit_name\u201d field\u2026In this small example it\u2019s irrelevant, but when I\u2019m querying millions of records, many of which do not have a fruit_name field, it makes a huge difference. I want to just \u201cbypass\u201d the lookup operation in this case for these records. Maybe @Asya_Kamsky has an idea, she is a genius.\nCode:"}, {"role": "assistant", "content": "Text:One idea that comes to mind is that you could use $facet.One will start with$match : { \"fruit_name\" : { \"$exists\" : 1 } }and do the $lookup while the other will start with$match : { \"fruit_name\" : { \"$exists\" : 0 } }The issue I see is that each facet is limited to 16Gb which may or may not be an issue.The other thing you could try is do 2 aggregations in a transaction. But I am not sure it is possible to do aggregations inside transactions.Why 2 normal aggregations do not work?Have you looked at the new $lookup variants with which you can have conditions and sub-pipeline?\nCode:$match : { \"fruit_name\" : { \"$exists\" : 1 } }$match : { \"fruit_name\" : { \"$exists\" : 0 } }"}, {"role": "user", "content": "Text:Because the example is part of a much larger aggregation doing other pipeline operations. So running it as two separate aggregations is much less optimal. And yes, $facet hitting that limit would be an issue (it\u2019s 16mb, not Gb\u2026 Gb would be great lol).But I appreciate the thought!It would be awesome if there was a way to only conditionally $lookup. Oh well!\nCode:"}, {"role": "assistant", "content": "Text:$facet is definitely not the way to go. However, if the field you are doing $lookup on is an empty array then it won\u2019t match anything in the foreign collection (because array is used sort of as {$in:[]} which matches nothing.So the solution to your problem may just be to fill in something like: {$set:{fruit_name:{$ifNull:[\"$fruit_name\", [] ]}}} before the $lookup and the empty [] as localField won\u2019t match anything, unlike null or missing field.Asya\nCode:$facet$lookup{$in:[]}{$set:{fruit_name:{$ifNull:[\"$fruit_name\", [] ]}}}$lookup[]localField"}, {"role": "assistant", "content": "Text:And since $unionWith was added in 4.4 you can also do two aggregations within the same aggregation pipeline, btw.Asya\nCode:$unionWith"}, {"role": "user", "content": "Text:So the solution to your problem may just be to fill in something like: {$set:{fruit_name:{$ifNull:[\"$fruit_name\", [] ]}}} before the $lookup and the empty [] as localField won\u2019t match anything, unlike null or missing field.Awesome, thank you, I\u2019ll give that a go. Isn\u2019t this a more common occurrence? I would think that doing a $lookup against a related collection defined by an optional field happens quite a bit, so it seems to be there should be a more straightforward way to do this? Or am I just bonkers?Thanks again.\nCode:{$set:{fruit_name:{$ifNull:[\"$fruit_name\", [] ]}}}$lookup[]localField"}, {"role": "assistant", "content": "Text:i am stuck with same case where i am trying to do a lookup with same collection as ben but i have the fruit_name fields already as an empty array [].\nbut it doesnt returns the another documentmy aggregate query\ndb.child_fruits.aggregate([\n{ $match: {\n_id: ObjectId(\u2018624c577bc98e24f398b012ad\u2019)\n}\n},\n{ $lookup: {\nfrom: \u2018fruit\u2019,\nlocalField: \u2018fruit_name\u2019,\nforeignField: \u2018name\u2019,\nas: \u2018fruitDetails\u2019\n}\n},\n{ $unwind: { path: \u2018$fruitDetails\u2019 } }\n])\nCode:"}, {"role": "assistant", "content": "Text:{$set:{fruit_name:{$ifNull:[\"$fruit_name\", ]}}}Thank you. This helped\nCode:"}, {"role": "assistant", "content": "Text:Won\u2019t this still run a lookup on the record with empty field even though it won\u2019t match anything?\nCode:"}, {"role": "assistant", "content": "Text:For anyone coming here, $unionWith is the way to go.\nTo use the original question\u2019s context, in your aggregation, initially match the records where fruit_name is null, then union that with the records where fruit_name is defined, and perform the lookup operation within the unionWith pipeline. Something like this:\nCode:$unionWithfruit_namefruit_namedb.child_fruit.aggregate([\n { $match: { fruit_name: null }},\n { $unionWith: {\n coll: \"child_fruit\",\n pipeline: [\n { $match: { fruit_name: { $ne: null }}},\n { $lookup: {\n from: \"fruit\",\n ...\n }}\n ]\n },\n ...\n]);\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongodb Compass dialog not opening and tags: ['compass']"}, {"role": "user", "content": "Text:I have installed MongoDB on Windows Server 2019. It installs successfully and the service is running on 27017. The Compass icon is on the desktop, however when I try to open it nothing happens. I\u2019ve tried both double-clicking the icon and going to the file location and running it from the command line, and it still the Compass application will not open. Is there some log file I can check to see what went wrong? Thanks.\nCode:"}, {"role": "assistant", "content": "Text:Did Compass install went fine?What is the version\nThere is no log for Compass\nNormally it should open Compass screen when you click on the icon\nDo you have shell installed on your pc?Can you connect to mongod\nShow us screenshots\nCode:"}, {"role": "assistant", "content": "Text:There is, actually, a log file. It\u2019s not yet mentioned in the docs but it\u2019s there.The easiest way to access the log file is from Compass itself (Help > Open Log File) but this is not useful in this case.You should find your logs in %USERPROFILE%\\AppData\\Local\\mongodb\\compass.\nCode:%USERPROFILE%\\AppData\\Local\\mongodb\\compass"}, {"role": "assistant", "content": "Text:I\u2019m having the same issue with Windows Server 2019. With a fresh install of MongoDB, Compass interface will not show. The process is running in the taskmgr but no GUI\nCode:"}, {"role": "assistant", "content": "Text:Check these links\nCode:"}, {"role": "assistant", "content": "Text:Was Compass installed with the EXE? If yes, it\u2019s a known issue that we are looking into. I would recommend using the MSI installer.\nCode:"}, {"role": "assistant", "content": "Text:I used mongoDB msi installer and compass got installed with it. mongodb-windows-x86_64-5.0.6-signed. Is that what you are referring to?\nCode:"}, {"role": "assistant", "content": "Text:Ah, I see. Can you try reinstalling Compass using its own MSI? You can find it here: MongoDB Compass Download | MongoDB.\nCode:"}, {"role": "assistant", "content": "Text:Hello.I uninstalled the previous version and installed the version you suggested and it worked fine. Thanks for taking the time to address this.Regards\nCode:"}, {"role": "assistant", "content": "Text:i downloaded and installed mongodb compass but .exe file is not inside the bin folder and mongodb icon also not open in desktop i dont know how to open the campass local desktop. before i used mongodb once installed it will open automatically now campass is not opening please give some suggestion?\nCode:"}, {"role": "assistant", "content": "Text:What is your os?\nYou should see executable file.May be you are checking under mongodb/bin\nCheck under Compass install directory\nOn Windows from programs you can find Compass\nor go to installed directory you will find Compass executable\nCode:"}, {"role": "assistant", "content": "Text:I tried it with MSI but after installation when I try opening the compass its not opening at all. How can i open it? Thanks!\nCode:"}, {"role": "assistant", "content": "Text:What error are you getting?\nPl show with a screenshot\nDid you try from bin dir clicking on the executable\nCode:"}, {"role": "assistant", "content": "Text:I have installed Compass and when I try to open Compass by clicking on MongoDB Compass nothing happens my. I have tried opening it from the bin location as well; again nothing happens. I currently using windows 8.1. Do I need a newer version of windows?\nCode:"}, {"role": "assistant", "content": "Text:Is your Windows 32bit or 64bit?\nMongodb supports only 64bit\nAs per download page Win64-bit 8.1+ version needed to install 1.10.1 version\nCode:"}, {"role": "assistant", "content": "Text:Thanks for the reply! I have 64 bit windows 8.1 on my computer.\nCode:"}, {"role": "assistant", "content": "Text:I too am using Windows 8.1.It seems there is no msi for downloading Compass at:MongoDB Compass, the GUI for MongoDB, is the easiest way to explore and manipulate your data. Download for free for dev environments.I went here and expanded the assets to find the .msi although I used the .exe file which worked fine:The GUI for MongoDB. Contribute to mongodb-js/compass development by creating an account on GitHub.I got Version 1.36.4 working although 1.37 may have worked (I want to get to work and I\u2019m too lazy to mess with it right now).\nCode:"}, {"role": "assistant", "content": "Text:I tried .exe and. zip as well but they didn\u2019t too, so I upgraded my system instead.\nCode:"}, {"role": "assistant", "content": "Text:I had the same problem with the last version 1.38.2. I\u2019ve updated the from 1.37. The program does not run.\nLooking in the Application Logs of Windows: I\u2019ve got Exception code: 0x80000003.\nI\u2019ve tried to install it on Windows Server 2022. The same problem.\nThe only solution is to install again the 1.37 version.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Trouble importing JSON array of objectID {$oid:XXX} and tags: ['node-js', 'compass', 'database-tools']"}, {"role": "user", "content": "Text:I have been wrestling with trying to import JSON \u2013 using mongoimport or the Javascript insert/replace calls \u2013 an array of mongo ObjectIds.According to Mongo docs, to specify a Mongo Id in JSON, one uses {\u201c$oid\u201d:XXXX}.The long and short of it is that if the data is in a JSON array, the mongo import \u2013 both command line and API \u2013 does not recognize {\u201c$oid\u201d:XXXX} and convert it to an Object Id.Below is a test case, using Compass as the viewer, and what I see is the array members are not recognized as ObjectIds. I have no idea if this is a bug, or a feature. It even manifests itself with JSON.stringify.Given a test case where we insert the JSON belowWhen we retrieve the data we get:\nCode:{\n\"_id\": {\"$oid\": \"fa3e6fe626f94cdfe8558a6e\"},\n\"members1\": [\n{\"$oid:\": \"6d51c5346c5060a572c4cbc7\"},\n{\"$oid:\": \"fe8ce32ad418303ed38aec47\"},\n{\"$oid:\": \"9d4076461b20770443d46327\"},\n{\"$oid:\": \"28b730141139503b00128eb4\"}\n],\n\"members2\": {\n\"1\": {\"$oid\": \"6d51c5346c5060a572c4cbc7\"},\n\"2\": {\"$oid\": \"fe8ce32ad418303ed38aec47\"},\n\"3\": {\"$oid\": \"9d4076461b20770443d46327\"},\n\"4\": {\"$oid\": \"28b730141139503b00128eb4\"}\n},\n\"embed1\": {\"2\": {\"$oid\": \"fe8ce32ad418303ed38aec47\"},\n\"_id\": {\"$oid\": \"6d51c5346c5060a572c4cbc7\"}\n},\n\"embed2\": {\"type\": \"vessel-status\",\n\"lookupValue\": \"A\",\n\"description\": \"Active\",\n\"isActive\": true,\n\"isAshop\": true,\n\"isWcgop\": true,\n\"_id\": {\"$oid\": \"6d51c5346c5060a572c4cbc7\"}\n},\n\"parent\": {\"$oid\": \"d9630c927bc17266f4549426\"}\n}\nt> db.resources.findOne(ObjectId('fa3e6fe626f94cdfe855\n8a6e'))\n{\n _id: ObjectId(\"fa3e6fe626f94cdfe8558a6e\"), \n members1: [\n { '$oid:': '6d51c5346c5060a572c4cbc7' }, \n { '$oid:': 'fe8ce32ad418303ed38aec47' }, \n { '$oid:': '9d4076461b20770443d46327' }, \n { '$oid:': '28b730141139503b00128eb4' } \n ],\n members2: {\n '1': ObjectId(\"6d51c5346c5060a572c4cbc7\"),\n '2': ObjectId(\"fe8ce32ad418303ed38aec47\"),\n '3': ObjectId(\"9d4076461b20770443d46327\"),\n '4': ObjectId(\"28b730141139503b00128eb4\")\n },\n embed1: {\n '2': ObjectId(\"fe8ce32ad418303ed38aec47\"),\n _id: ObjectId(\"6d51c5346c5060a572c4cbc7\")\n },\n embed2: {\n type: 'vessel-status',\n lookupValue: 'A',\n description: 'Active',\n isActive: true,\n isAshop: true,\n isWcgop: true,\n _id: ObjectId(\"6d51c5346c5060a572c4cbc7\")\n },\n parent: ObjectId(\"d9630c927bc17266f4549426\")\n}\n\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB Aggregation - Does $unwind order documents the same way as the nested array order? and tags: ['aggregation']"}, {"role": "user", "content": "Text:I am wandering whether using $unwind operator in aggregation pipeline for document with nested array will return the deconstructed documents in the same order as the order of the items in the array.\nExample:\nSuppose I have the following documentsI would like to use paging for all values in all documents in my application code. So, my idea is to use mongo aggregation framework to:So the question using the example described above is:Is it guaranteed that the following aggregation pipeline:will always result to the following documents with exactly the same order?:\nCode:{ \"_id\" : 1, \"item\" : \"foo\", values: [ \"foo\", \"foo2\", \"foo3\"] }\n{ \"_id\" : 2, \"item\" : \"bar\", values: [ \"bar\", \"bar2\", \"bar3\"] }\n{ \"_id\" : 3, \"item\" : \"baz\", values: [ \"baz\", \"baz2\", \"baz3\"] }\nvalues[\n {$sort: {\"_id\": 1}},\n {$unwind: \"$values\"}\n]\n{ \"_id\" : 1, \"item\" : \"foo\", values: \"foo\" }\n{ \"_id\" : 1, \"item\" : \"foo\", values: \"foo2\" }\n{ \"_id\" : 1, \"item\" : \"foo\", values: \"foo3\" }\n{ \"_id\" : 2, \"item\" : \"bar\", values: \"bar\" }\n{ \"_id\" : 2, \"item\" : \"bar\", values: \"bar2\" }\n{ \"_id\" : 2, \"item\" : \"bar\", values: \"bar3\" }\n{ \"_id\" : 3, \"item\" : \"baz\", values: \"baz\" }\n{ \"_id\" : 3, \"item\" : \"baz\", values: \"baz2\" }\n{ \"_id\" : 3, \"item\" : \"baz\", values: \"baz3\" }\n"}, {"role": "assistant", "content": "Text:Hello @karaimin welcome to the community!There is a chance that you get the same results but no guarantee. Personally I always use the sort after the unwind, ideal with an $match before the unwind to try to get as few documents as possible.The above will provide for sure the wanted result. However, I hope that one oft the MDB internals can elaborate onCheers,\nMichael\nCode:$match[\n {$match: { } }\n {$unwind: \"$values\"}\n {$sort: {\"_id\": 1}},\n]\n"}, {"role": "user", "content": "Text:Thank you @michael_hoeller for you response.\nHowever, maybe this is not an option for me since I expect the real sample to have a small number documents which I will $match by some query (this is why I am sorting them by _id) and large number of items in values array.\nAs I mentioned I want to use pagination for the items in the values attribute. So I need a consistent order of them. Sorting them is not an option since after $unwind I loose the DB Index and it will exceed the memory of 100MB available for the pipeline. I can use \"allowDiskUse: true\", but that is also not a good option because it will slow down queries a lot.\nCode:valuesvalues\"allowDiskUse: true\""}, {"role": "assistant", "content": "Text:Hello @karaiminI can use \"allowDiskUse: true\" , but that is also not a good option because it will slow down queries a lot.Yes, that should be avoid when you are acting in a realtime app.One thought on this, large arrays are almost always difficult to handle. Maybe you can change your schema and use embedding for $values? This would open completely different options.You can check if a multikey Index on one or some fields in your array can help. In case you can find a good index you can walk along the index without the $unwindsince after $unwind I loose the DB IndexI am not sure what you mean. When you deconstruct an array with $unwind you will get an document per field and element. You can add the option includeArrayIndex to $unwind. This will add an field to the new document which just numbers the fields. This could also provide a path to go.In general, to retrieve page \u2018n\u2019 the code looks like this:As the size of your data increases, this approach has performance problems. The reason is that every time the query is executed, the full result set is built up, then the server has to walk from the beginning of the collection to the specified offset. As your offset increases, this process gets slower. Also, this process does not make efficient use of the indexes. So typically the \u2018skip()\u2019 and \u2018limit()\u2019 approach is useful when you have small data sets,The reason the previous approach does not scale well is the skip() command. Depending how you have build your _id you may can use the natural order in the stored data like a timestamp, or an index (pls s. above).This approach leverages the inherent order that exists in the \u201c_id\u201d field. Also, since the \u201c_id\u201d field is indexed by default, the performance of the find operation is very good.There are further options to do pagination:both I do not think will help here so I skip the examples.Cheers,\nMichael\nCode:\"allowDiskUse: true\"includeArrayIndex{ \"_id\" : 1, \"arrayIndex\" : NumberLong(0), \"item\" : \"foo\", values: \"foo\" }\n{ \"_id\" : 1, \"arrayIndex\" : NumberLong(1), \"item\" : \"foo\", values: \"foo2\" }\n{ \"_id\" : 1, \"arrayIndex\" : NumberLong(2), \"item\" : \"foo\", values: \"foo3\" }\n{ \"_id\" : 2, \"arrayIndex\" : NumberLong(1), \"item\" : \"bar\", values: \"bar\" }\n{ \"_id\" : 2, \"arrayIndex\" : NumberLong(2), \"item\" : \"bar\", values: \"bar2\" }\n{ \"_id\" : 2, \"arrayIndex\" : NumberLong(3), \"item\" : \"bar\", values: \"bar3\" }\n// Page 1\ndb.users.find().limit (10)\n// Page 2\ndb.users.find().skip(10).limit(10)\n// Page 3\ndb.users.find().skip(20).limit(10)\ndb.users.find().skip(pagesize*(n-1)).limit(pagesize)\n// Page 1\ndb.users.find().limit(pageSize);\n// Find the id of the last document in this page\nlast_id = ...\n\n// Page 2\nusers = db.users.find({` `'_id'` `> last_id}). limit(10);\n// Update the last id with the id of the last document in this page\nlast_id = ...\n$slice"}, {"role": "user", "content": "Text:Hi @michael_hoellerI didn\u2019t get your idea here:Maybe you can change your schema and use embedding for $values? This would open completely different options.If you mean changing my schema to looks similar to what $unwind does (reversing One-to-Many relation) and adding appropriate key index for each value will do the trick, but this schema also has a lot of concerns related to my other scenarios.I am not sure what you mean.I mean that now I may have a single key index on values field (used for queries), but after $unwind it is useless. So, next stage (which is $sort) won\u2019t benefit from the sorted structure of the indexes in the B-Tree just like regular $sort operation on indexed field.My example is similar to the bucket pattern. The large document (with a too large array) is partitioned to some small documents (with smaller array size) in order to fit in the max document size.\nKeeping too many documents will lead to heavy update operations (sometimes including massive amount of documents ) which I try to avoid.\nCode:values"}, {"role": "assistant", "content": "Text:The same question:Does $unwind keep the \u201cunwound\u201d documents in the same order as they were ordered in the source array?Need to know this as we would like to avoid an unneeded $sort that would require allowDiskUse: true (when the aggregation otherwise doesn\u2019t). Couldn\u2019t find anything about this in the docs.It seems potentially reasonable to assume that it would be in the same order, but can we be sure? @karaimin did you figure it out?\nCode:$unwind$sortallowDiskUse: true"}, {"role": "user", "content": "Text:No @qtax, I didn\u2019t find appropriate solution. I didn\u2019t find any information in the official documentation and according to @michael_hoeller the order is not guaranteed, so I assume that I don\u2019t have any evidence to rely on the returned order.\nI solve the problem with aggregation pipeline that sort the documents and give me the length of each nested array. After that with some application logic I am able to reduce the documents where my next page is. Then, I query only the filtered documents and this way the pagination is achieved. It is not so efficient like the assumption described in the first question but for now it is the best I have found.\nCode:"}, {"role": "assistant", "content": "Text:Hello @karaimin and @qtax,thanks for updating, I lost your message on my bookmarks.according to @Michael the order is not guaranteedThis was my experience in an previous customer project. The \u201cunwound\u201d documents are identical to the input document except for the value of the array field which now holds a value from the original array element. It seems that the documents are created by the sequence they occur in the array. I assume that one unwind can be idempotent but within the the flow of a process you might get side effects (e.g. empty array).\nIn case you need to keep the sequence you can add includeArrayIndex which will add a field to the unwound document which holds the position of the field in the previous array.To be absolutely sure what is correct I hope that @Asya_Kamsky can step in?regards,\nMichael\nCode:arrayincludeArrayIndex"}, {"role": "user", "content": "Text:Hi @michael_hoellerI know the existence of includeArrayIndex option. However I would like to avoid application level sorting. So, saying in other words:Is there any chance that this:may be destructed to this.Take a look at the order (1 0 2)Having only the index won\u2019t solve our problem. We need application level sorting if the above sequence is returned.\nBest Regards\nAleydin\nCode:includeArrayIndex{ \"_id\" : 1, \"item\" : \"foo\", values: [ \"foo\", \"foo2\", \"foo3\"] }\n{ \"_id\" : 1, \"item\" : \"foo\", values: \"foo2\", \"arrayIndex\" : NumberLong(1 }\n{ \"_id\" : 1, \"item\" : \"foo\", values: \"foo\", \"arrayIndex\" : NumberLong(0 }\n{ \"_id\" : 1, \"item\" : \"foo\", values: \"foo3\", \"arrayIndex\" : NumberLong(2 }\n"}, {"role": "assistant", "content": "Text:Hi @karaiminI understood your question, I have seen this happen in a project some month back. I did tests just for me, but I have not been able to recreate the issue. To be on the save side on customer projects, I did add an extra(?) sort. This is a good question! With the last message I \u201cpinged\u201d @Asya_Kamsky she probably can add the full insight.\nJust do not want to limt this to Asya she is often abroad, anyone else around who can add on this?Regards,\nMichael\nCode:"}, {"role": "user", "content": "Text:Ok, Thank you @michael_hoeller for all your support. I am looking forward of further updates on this topic. I will be glad to see official statement from the MongoDB staff.\nCode:"}, {"role": "assistant", "content": "Text:Hi there folks,Yes, the order of documents will be the same as the order of elements in the array and the order pre-unwind will be preserved.But using $skip and $limit for pagination is not really a good idea as it\u2019s not very performant, especially once you move to sharding\u2026Asya\nCode:"}, {"role": "assistant", "content": "Text:Hello Asya,\nthanks for clearing that, lucky to save an extra sort in the future. Concerning pagination I provided some suggestions fairly at the beginning of the post.\nMichael\nCode:"}, {"role": "user", "content": "Text:Thanks @Asya_Kamsky and @michael_hoeller for your time on revealing the mystery \u2026 and the suggestions about the pagination approach.Since, $unwind will be used, I won\u2019t be able to benefit from an indexed field and $skip and $limit is my only option for pagination (with this data model). I am going to test it if it can suits our needs. Maybe, combination from both \u201c$skip/$limit\u201d for the first few pages and the approach I described above can be appropriate for me.Best Regards\nAleydin\nCode:"}, {"role": "assistant", "content": "Text:Yes, the order of documents will be the same as the order of elements in the array and the order pre-unwind will be preserved.Thanks for sharing this statement, and I gather you are a very reputable source, having worked on the aggregation framework itself.It seems a colleague of yours contradicted this statement in a different forum thread a few months later sayng \u201cMongoDB only gurantee order of documents based on a sort operation\u201d which leaves me unsure whether it would be safe to avoid a sort operation (for performance reasons) when performing $unwindIs there any up-to-date definititve documentation on what guarantees there are regarding array ordering during aggregation?\nCode:$unwind"}, {"role": "assistant", "content": "Text:There is no contradiction.The $unwind preserves the order of the documents it receives and the order of the array elements.To get a predictable order of documents you must $sort.That is if you $sort before $unwind, documents will be sorted after $unwind.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Error in finding the user MongooseError: Operation `users.findOne()` buffering timed out after 10000ms and tags: ['node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:i use cmd in terminal npm start and it start at port 5000 and also connect mongo db and when i brows localhost://5000 in browser, it open but when i sign up in it then in browser porcesssing only not any response.and when i see in terminal it show me error Express server is up and running on port 5000\nSuccessfully connected to db cars\nError in finding the user MongooseError: Operation users.findOne() buffering timed out after 10000ms\nat Timeout. (C:\\Users\\Irfan Ansari\\Desktop\\IssueTracker\\node_modules\\mongoose\\lib\\drivers\\node-mongodb-native\\collection.js:175:23)\nat listOnTimeout (node:internal/timers:564:17)\nat process.processTimers (node:internal/timers:507:7)\nError in finding the user MongooseError: Operation users.findOne() buffering timed out after 10000ms\nat Timeout. (C:\\Users\\Irfan Ansari\\Desktop\\IssueTracker\\node_modules\\mongoose\\lib\\drivers\\node-mongodb-native\\collection.js:175:23)\nat listOnTimeout (node:internal/timers:564:17)\nat process.processTimers (node:internal/timers:507:7)so pls solve it\nCode:users.findOne()users.findOne()"}, {"role": "user", "content": "Text:C:\\Users\\Irfan Ansari>mongosh\nCurrent Mongosh Log ID: 63cbdffba0f2600a491b9ec3\nConnecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.2\nMongoServerSelectionError: Server selection timed out after 2000 msC:\\Users\\Irfan Ansari>\nCode:"}, {"role": "assistant", "content": "Text:you can try this: Go to data services tab security on the left side and find network access inside that you choose to add the IP address and add 0.0.0.0/0 this IP address means you can access to database from any network address\nCode:"}, {"role": "assistant", "content": "Text:MongooseError: Operation users.findOne() buffering timed out after 10000ms\nat Timeout. (C:\\Users\\Hassan Dawood\\Documents\\commercehope-backend\\node_modules\\mongoose\\lib\\drivers\\node-mongodb-native\\collection.js:\n185:23)\nat listOnTimeout (node:internal/timers:569:17)\nat process.processTimers (node:internal/timers:512:7)\nCode:users.findOne()"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: [MongoDB .local Events] MongoDB is heading out on a World Tour! and tags: ['london-mug', 'newyork-mug', 'saopaulo-mug', 'mexico-mug']"}, {"role": "user", "content": "Text:Email_Local-Series1200\u00d7500 613 KBHello All!MongoDB is heading out on a world tour to bring the best, most relevant content directly to you! Join us to connect with MongoDB experts, meet fellow users building the next big thing, and be among the first to hear the latest announcements!Register Now with **MUG50** discount code to get 50% off! For India-based events use Invite Code **MDB.Community.23** to register yourself for the event. Keynote Presentations: Learn about the latest product announcements from MongoDB industry leaders. Technical Sessions: Experience educational technical sessions for all levels, delivered by MongoDB experts and customers.Relational Migrator\nLearn how to easily migrate a relational database to MongoDB with one-time or continuous data migration.Data Modeling\nLearn data modeling principles, and take your models to the next level with tips and tricks from the experts.Atlas Search:\nExplore the Atlas Search ecosystem and how you can use it to effortlessly integrate search into your applications. MongoDB Product Demos: Stop by the MongoDB booth for demos of the latest products and to get your questions answered. Networking: Meet with our MongoDB enthusiasts in your area to share ideas and expand your network.Join our regional virtual user groups to connect with MongoDB Community in your region and stay updated on events in your time zone! Use code MUG50 for 50% off your ticket!!\n Use Invite Code MDB.Community.23 for .locals in IndiaUpcoming Events:We look forward to seeing you at these events! \nCode:**MUG50****MDB.Community.23**"}, {"role": "assistant", "content": "Text:We\u2019re looking forward to meeting community members at these events! Please share if you\u2019re planning to attend!\nCode:"}, {"role": "assistant", "content": "Text:Hey regarding the MongoDB.local Bangalore event, it\u2019s mentioned that it\u2019s free of cost to attend. In that case, should I use MUG50 as invite code?\nCode:"}, {"role": "user", "content": "Text:Hey @_karanel,\nFor India-based .locals you could use MDB.Community.23 to register for the event \nCode:MDB.Community.23"}, {"role": "assistant", "content": "Text:Hey @Harshit, actually I registered with my work email (karan@phoenixrp.io) without a code entering it as \u201cNA\u201d, and I can\u2019t register again.\nCould you help me out? \nCode:"}, {"role": "user", "content": "Text:No problem @_karanel. You don\u2019t need to register again.\nWe will let the team know about it Looking forward to seeing you at the event!\nCode:"}, {"role": "assistant", "content": "Text:Hey @Harshit, I registered with my work email with a code entering it as \u201cyogesh\u201d, I can\u2019t register again.\nCould you please help?\nCode:"}, {"role": "user", "content": "Text:Hey @yogesh_mishra,\nLet us check with the team and help you out. Could you also in the meantime, use the \u201cContact the Organiser\u201d button on the registration page to share your concern.https://events.mongodb.com/mongodb-local-delhincr\nCode:"}, {"role": "assistant", "content": "Text:I am a student. Which Email should I use for .local Mumbai to register as it is not accepting my personal email. Should I use my college email instead?\nCode:"}, {"role": "assistant", "content": "Text:Yes, you can probably use your college email.\nCode:"}, {"role": "assistant", "content": "Text:Registered. See y\u2019all there!\nCode:"}, {"role": "assistant", "content": "Text:Thanks for sharing Harshit, would be there in the Boston Meetup.\nCan you also update if there would be any events in Canada for this tour - Toronto/Vancouver?Thanks.\nCode:"}, {"role": "assistant", "content": "Text:Hi Devang - thanks for your interest! We are starting a MongoDB User Group in Boston in late October after the .local event. You can go ahead and join here: Boston, us: mongodb user group - MongoDB Developer Community ForumsThere aren\u2019t any .local events in Canada this year.\nCode:"}, {"role": "assistant", "content": "Text:Robbed, Toronto was robbed I say! \nCode:"}, {"role": "assistant", "content": "Text:Hi, I registered for the .local Bengaluru event, but I didn\u2019t receive any confirmation email.Can you please tell by when we will receive the confirmation for this event?\nCode:"}, {"role": "user", "content": "Text:Hey @rakesh_verma24,\nOur team is currently in the process of sending out confirmations for the event. We understand that this may cause some anticipation. Also, preference is being given to professionals as the content is tailored to their needs.In the meantime, we invite you to join our Bangalore User Group to stay informed about any upcoming meetups in the region.Thanks\nHarshit\nCode:"}, {"role": "assistant", "content": "Text:26th August Ahmmedabad is missing.\nCode:"}, {"role": "user", "content": "Text:Hey, @Anjesh_Agrawal That is our MongoDB User Group Meetup event run and managed by the community leaders, while these .locals are larger day-long events, majorly run by MongoDB Staff. It has around 7-8 sessions, booths and ask the experts sections to interact with MongoDB staff.This year .locals in India are being held in Bengaluru, Delhi and Mumbai. \nCode:"}, {"role": "assistant", "content": "Text:hello , i registered for MongoDB .local mumbai but didn\u2019t received any acknowledgment about the event ,\ni even wrote the mail to organizer didnt receive any response, either the computergenerated nor thereply mail\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: I am getting this error const serverSelectionError = new ServerSelectionError(); and tags: ['node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:The application successfully started on 27017\nD:\\web\\web developement\\Dance website pug\\node_modules\\mongoose\\lib\\connection.js:807\nCode: const serverSelectionError = new ServerSelectionError();\n ^\n\nMongooseServerSelectionError: Invalid message size: 1347703880, max allowed: 67108864\n at NativeConnection.Connection.openUri (D:\\web\\web developement\\Dance website pug\\node_modules\\mongoose\\lib\\connection.js:807:32)\n at D:\\web\\web developement\\Dance website pug\\node_modules\\mongoose\\lib\\index.js:342:10\n at D:\\web\\web developement\\Dance website pug\\node_modules\\mongoose\\lib\\helpers\\promiseOrCallback.js:32:5\n at new Promise ()\n at promiseOrCallback (D:\\web\\web developement\\Dance website pug\\node_modules\\mongoose\\lib\\helpers\\promiseOrCallback.js:31:10)\n at Mongoose._promiseOrCallback (D:\\web\\web developement\\Dance website pug\\node_modules\\mongoose\\lib\\index.js:1181:10)\n at Mongoose.connect (D:\\web\\web developement\\Dance website pug\\node_modules\\mongoose\\lib\\index.js:341:20)\n at Object. (D:\\web\\web developement\\Dance website pug\\app.js:10:10)\n at Module._compile (node:internal/modules/cjs/loader:1103:14)\n at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10) {\n reason: TopologyDescription {\n type: 'Unknown',\n servers: Map(1) {\n '127.0.0.1:27017' => ServerDescription {\n _hostAddress: HostAddress { isIPv6: false, host: '127.0.0.1', port: 27017 },\n address: '127.0.0.1:27017',\n type: 'Unknown',\n hosts: [],\n passives: [],\n arbiters: [],\n tags: {},\n minWireVersion: 0,\n maxWireVersion: 0,\n roundTripTime: -1,\n lastUpdateTime: 2786731,\n lastWriteDate: 0,\n error: MongoParseError: Invalid message size: 1347703880, max allowed: 67108864\n at processIncomingData (D:\\web\\web developement\\Dance website pug\\node_modules\\mongodb\\lib\\cmap\\message_stream.js:91:18)\n at MessageStream._write (D:\\web\\web developement\\Dance website pug\\node_modules\\mongodb\\lib\\cmap\\message_stream.js:28:9)\n at writeOrBuffer (node:internal/streams/writable:389:12)\n at _write (node:internal/streams/writable:330:10)\n at MessageStream.Writable.write (node:internal/streams/writable:334:10)\n at Socket.ondata (node:internal/streams/readable:754:22)\n at Socket.emit (node:events:526:28)\n at addChunk (node:internal/streams/readable:315:12)\n at readableAddChunk (node:internal/streams/readable:289:9)\n at Socket.Readable.push (node:internal/streams/readable:228:10) {\n [Symbol(errorLabels)]: Set(0) {}\n }\n }\n },\n stale: false,\n compatible: true,\n heartbeatFrequencyMS: 10000,\n localThresholdMS: 15,\n logicalSessionTimeoutMinutes: undefined\n },\n code: undefined\n"}, {"role": "assistant", "content": "Text:did you get sollution to this bug?\nCode:"}, {"role": "assistant", "content": "Text:This error is probably occur because the mongo dB services is not started yet what you have to do is\nGo to control panel\nDouble click on services\nthen search for mongodb.exe and then click on start\nits for window user\nI hope it would be work.\nCode:"}, {"role": "assistant", "content": "Text:/app/node_modules/mongoose/lib/connection.js:847\nsource_code-server-1 | const serverSelectionError = new ServerSelectionError();\nsource_code-server-1 | ^\nsource_code-server-1 |\nsource_code-server-1 | MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017After running the mongodb service i got the above error for docker\ndocker-compose.yamlversion: \u201c3.8\u201dservices:mongodb:server:client:volumes:data:logs:dockerfileFROM node:18.8.0WORKDIR /appCOPY package*.json /app/RUN npm installCOPY . /app/EXPOSE 4000CMD [ \u201cnpm\u201d, \u201cstart\u201d]Please help me.\nCode:image: \"mongo\"\n\nvolumes:\n\n - data:/data/db\nbuild: ./server\n\nports:\n\n - \"4000:4000\"\n\nvolumes:\n\n - logs:/app/logs\n\n - ./server:/app\n\n - /app/node_modules\n\ndepends_on:\n\n - mongodb\nbuild: ./client\n\nports:\n\n - \"3000:3000\"\n\nenvironment:\n\n - CHOKIDAR_USEPOLLING=true\n\nvolumes:\n\n - ./client/src:/app/src\n\nstdin_open: true\n\ntty: true\n\ndepends_on:\n\n - server\n"}, {"role": "assistant", "content": "Text:Hey I think your problem is that you don\u2019t have mongodb installed on your computer. Once you download it you can changeto\nCode:mongodbmongoose.connect('mongodb://localhost:27017/blog')\nmongoose.connect('mongodb://127.0.0.1/blog')\n"}, {"role": "assistant", "content": "Text:Thankyou this saved me haha\nCode:"}, {"role": "assistant", "content": "Text:Ok, changing the URI worked but why?!?! Ok I\u2019m using mongoose and found out why:from MS Edge\nCode:"}, {"role": "assistant", "content": "Text:this worked for me. thank you\nCode:"}, {"role": "assistant", "content": "Text:thank u, it was pain in my head\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Designing Mongo DB for Multi tenanted database and tags: ['data-modeling']"}, {"role": "user", "content": "Text:We are currently in process of designing a Multi tenant application, we choose to go with Mongo db for data storage. Our application needs to store different entities, like user, employee, payroll etc., We want to build a scalable platform where clients can onboard/offboard faster, and manage the solutions easily. We also wanted to isolate the customer data logically.We are discussing few options on Mongo db how to place the data -Few queries -Many Thanks\nCode:"}, {"role": "assistant", "content": "Text:Welcome to the community, @Thirumalai_M!Am I understanding correctly that the same application is to be used by multiple companies but with the same backend servicing all? Or will it be different deployments with a backend for each deployment? Generally you will want to store data for entities in collections so you\u2019d want a users collection, an employees collection etc. Is the isolation of customer data so that you can give access to the data on a database level or are there other reasons? Will your clients be able to access the database directly or only via your application?So per your questions:I\u2019m not sure what you mean with questions 3 and 4 - can you provide more information?\nCode:{\"name\": \"Naomi\", \"team\": \"Engineering Communications\", ...}"}, {"role": "user", "content": "Text:Thanks Naomi for the detailed response. Your answer to my queries gives what I feed for No1. I have few queries on No1 and will clarify for No3.Basically we are a SaaS provider company developing system, the tenants can be onboarded and store their data. There are multiple entities in our application. We are using docker/container for service layer, but database wise we have some confusion. Whether separate database per client, separate collection per client or documents to be segregated using partition key.As per your answer for No2, I understand going with one collection per client will create data model issue. Hence going with single database with one collection per client is not feasible approach.Using a one collection for one entity (for Ex: Employee) and having its own index/partition will not provide isolation. Our application is a heath care system, should be HIPPA compliance.I understanding going with a single database per client will make sense for our scenario. Please correct me if I am wrong in my understanding.\nCode:"}, {"role": "assistant", "content": "Text:If you are using MongoDB Atlas, you can control access based on field values using Realm Rules. This would allow you to use one collection per entity while restricting access to the client that the data belongs to. So you could have a rule that a user can only see data that matches the company associated to that user.If you are not using Atlas you can control access on a database or collection level. So you could use that to restrict access for a database per client for your scenario.\nCode:"}, {"role": "assistant", "content": "Text:@Thirumalai_M - my two cents - since it\u2019s going to be a Healthcare/HIPPA compliant - better to go with separate database per client, that gives the highest level of isolation and security and due to security & compliance: most clients usually may want to have the database deployed on their owned secured network (cloud or on-premise) only. At the same time - it also allows doing client specific customization\u2019s later, if required. Now, the major drawbacks of this approach is the cost and maintenance overhead etc.Had this been a non-healthcare system - you could have even thought of having single collection for all clients but segregating their rows/documents based on additional \u201ctenant_id\u201d column. Although, it only provides only logical level of isolation but it\u2019s very easier to maintain and very cost effective. Depending on the number of clients/customers - you can easily scale it by having multiple shard clusters across - may be 1 for each and/or group of customers combined into one cluster i.e. tenant_id = 1 to 10 or tenant_name = A to M and tenant_id = 11 to 20 or tenant_name = M to Z into another cluster.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Advice for Chat schema design and tags: ['data-modeling']"}, {"role": "user", "content": "Text:Hi, in my application I\u2019m developing I need to allow for chats between any 2 users. I have the following schema in mind for a Messages collection:userID1 will always be the first user to start the chat, I\u2019ll save this for every Chat room consisting of 2 people. (EDIT: Should I use lexicographical ordering instead, with userID1 coming before userID2?)I\u2019ll create an index on the timestamp field so I can sort it in reverse, and then I can do the following to get the data every time the chat room is loaded (with pagination as you scroll up):And this I think should give me my intended behavior.Appreciate any advice, thanks.\nCode:{\n _id: ObjectId(),\n userID1: \"userA_ID\",\n userID2: \"userB_ID\",\n sender: \"one of the users\",\n message: \"some text\",\n timestamp: time\n}\nuserID1db.find({ userID1, userID2 }).sort({ \"timestamp\" : -1 })\n .skip(offset).limit(limit)\n"}, {"role": "assistant", "content": "Text:db.find({ userID1, userID2 }).sort({ \"timestamp\" : -1 })That particulate query will be better serve with a compound index on userID1,userID2,timestamp. See Performance Best Practices: Indexing | MongoDB Blog for the specifics.\nCode:db.find({ userID1, userID2 }).sort({ \"timestamp\" : -1 })"}, {"role": "assistant", "content": "Text:In your schema you might want also want to add a field \u201csent_by\u201d or something similar, this way you could moderate / find messages by users with a search feature.\nCode:"}, {"role": "user", "content": "Text:Thanks for pointing this out, it\u2019s a necessity actually. Otherwise I have no way of knowing who actually sent the message, oversight on my part.\nCode:"}, {"role": "user", "content": "Text:I wonder if I should use lexicographical sorting to determine userID1 and userID2, with userID1 coming before userID2, instead of who initiates the chat first.\nCode:"}, {"role": "assistant", "content": "Text:Could you merge userID1, userID2 and sender into just 2 fields?sender rather than userID1\nreceiver rather than userID2This would reduce the size of each document.\nCode:"}, {"role": "user", "content": "Text:Thanks for the suggestion, that makes a lot of sense, then the accompanying query would be the following right?So I would then have to create a multikey index on the sender, receiver and timestamp fields?\nCode:db.find({ $or: [{ sender: userA, receiver: userB }, { sender: userB, receiver: userA }]}\n .sort({ timestamp: -1 }).skip(offset).limit(limit)\n"}, {"role": "assistant", "content": "Text:Another implementation you could do that would involve another collection is, when a new chat is created in a \u201cConversation\u201d collection you can add the information:Then in the message instead of UserID1 and UserID2 you would just have \u201cconversation_id\u201dThis way if the members of the group change you only have to change it once in the \u201cConversation\u201d collection and all messages referencing the ID will see the changes.This would be similar to a One-to-Many with reference\nCode:\n{ id: 123\n participants: ['user1', 'user2'],\n}\n{ sender: 'user1', \n message: 'Hello World', \n timestamp: time,\n converstationId: 123\n}\n"}, {"role": "user", "content": "Text:That\u2019s a nice approach! Thank you both for the insights and advice.I was wondering (which was my second question), is storing a huge amount of random chat data in a collection good practice? I say random because in the Messages collection the ordering will be jumbled up when different users communicate at different times. Although it has no effect on the end users, is that acceptable practice?A more traditional data structure would be perhaps to keep all this chat in an array within a document (but of course it\u2019s subject to the 16MB BSON size limit), but logically this means there\u2019s no way any messages are interleaved with other messages.\nCode:"}, {"role": "assistant", "content": "Text:In general I don\u2019t believe that collections with a lot of documents is an issue. As long as your queries are indexed it shouldn\u2019t be a problem.Blockquote\nA more traditional data structure would be perhaps to keep all this chat in an array within a document (but of course it\u2019s subject to the 16MB BSON size limit), but logically this means there\u2019s no way any messages are interleaved with other messages.MongoDB does have a bucket design pattern. In which you store related items in an array.You could have a field called \u201ctotal_messages\u201d that is the sum of all messages and once it hits a certain number it creates a second bucket so you stay within the 16MB limit and don\u2019t have the massive arrays anti pattern.\nAlthough this may be more complicated than is required.\nCode:{\n conversation_id: 12345,\n time: time,\n members: ['user1', 'user2'],\n messages: [\n {\n sender: 'user1', \n message: 'Hello World', \n timestamp: time\n },\n {\n sender: 'user1', \n message: 'Hello World', \n timestamp: time\n }],\n total_messages: 2\n}\n"}, {"role": "user", "content": "Text:Thank you for the links and explanation. That\u2019s a nice approach as well, but yes it comes with a massive array regardless, and queries become a little more complex.What we\u2019re doing now without using the bucket design pattern is essentially merging all of these potential arrays into one collection. I think I shall be going ahead with what\u2019s been discussed so far with the sender/receiver method.\nCode:"}, {"role": "assistant", "content": "Text:If you are working on a chat application that is great, I think you should have the feature to add more users.\nCode:"}, {"role": "assistant", "content": "Text:Hi thanks for this\u2026 but i need to know how to get all the results by sortedI have used this\u2026 but thing is every things are in result block and I want it to in one array so I can fetch previous messages with $limit and $skip so I can send back to API of user message\u2026\nhere is my sample dataI have made 3 messages collection document after 3 new document is created\u2026 i will make it 1000 in production\u2026\nand I have use another thing called $concatArray but its adding only fields which I explicitly give exampleit will add two result to messages but not to all of that result\nhere my demo MongoDB collections [{ \"_id\": { \"$oid\": \"63bd85a54ffc8dc686c0df5b\" }, \"message\": [ - Pastebin.com\nCode:\ndb.chats.aggregate(\n {\n /**\n * query: The query in MQL.\n */\n $match: {\n \"members\": {\n \"$all\": [\n ObjectId('63ad8631e0d6cfe452b80677'),\n ObjectId('63adadf287e482e6f128ec0e'), \n ]\n }\n },\n },\n {\n /**\n * Provide any number of field/order pairs.\n */\n $sort: {\n \"created_at\": -1\n }\n },\n {\n /**\n * specifications: The fields to\n * include or exclude.\n */\n $project: {\n \"_id\": 0,\n // \"members\": 1,\n \"result\": {\n $sortArray: {input: \"$message\", sortBy: {created_at: -1}}\n }\n }\n },\n)\nresult$limit$skip[\n {\n \"result\": [\n {\n \"uuid\": \"df359053-5b69-4fc3-ac42-57aaf70ec9d9\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00011\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:52:26Z\"\n }\n },\n {\n \"uuid\": \"0cfe04ab-ccf2-4eb9-8760-d3471f033ea6\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00010\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:52:15Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"fe54bf97-5dad-4d3f-ada8-ea1f1ab31039\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00010\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:52:14Z\"\n }\n },\n {\n \"uuid\": \"9face81d-b989-4662-a090-2f8f498b1a7b\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00010\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:52:12Z\"\n }\n },\n {\n \"uuid\": \"8578ce16-f3ac-4ceb-b779-0c1f3e8fec2f\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00010\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:51:02Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"ef6f12e0-b601-4377-8ff9-28921799985b\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00009\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:51:00Z\"\n }\n },\n {\n \"uuid\": \"6fcbcc3b-ff09-4e1c-9ce5-d73790911592\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00008\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:50:47Z\"\n }\n },\n {\n \"uuid\": \"fdde26cd-6688-466a-be61-37ac8e312a70\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00007\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:49:33Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"fdde26cd-6688-466a-be61-37ac8e312a70\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00007\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:49:33Z\"\n }\n },\n {\n \"uuid\": \"fb72bef2-ceff-4e22-80cd-b54da6ba6f01\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00006\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:48:51Z\"\n }\n },\n {\n \"uuid\": \"3ffee1e6-8eb4-4a93-99a2-329576dc7754\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00005\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:48:34Z\"\n }\n },\n {\n \"uuid\": \"927726bd-acc9-461b-98db-9ce07cca5ff0\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00004\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:48:31Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"927726bd-acc9-461b-98db-9ce07cca5ff0\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00004\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:48:31Z\"\n }\n },\n {\n \"uuid\": \"664cb8fb-0284-4ad2-af1f-d9458fb09c24\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00003\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:48:25Z\"\n }\n },\n {\n \"uuid\": \"460e8a5a-327f-47c9-a8c3-76772cca4cc7\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:22:03Z\"\n }\n },\n {\n \"uuid\": \"ed4e5060-45f9-4f4a-a6a0-e45eddbd64bc\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:22:03Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"a45e6738-afb4-47aa-a8f4-fdf1d70eeb5f\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:22:03Z\"\n }\n },\n {\n \"uuid\": \"466b8569-12c4-4d06-8572-eb5999f0e4ae\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:22:03Z\"\n }\n },\n {\n \"uuid\": \"314b60eb-1eaf-4a72-a7a6-528ab474a0d9\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:22:03Z\"\n }\n },\n {\n \"uuid\": \"460e8a5a-327f-47c9-a8c3-76772cca4cc7\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:22:03Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"a45e6738-afb4-47aa-a8f4-fdf1d70eeb5f\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:22:03Z\"\n }\n },\n {\n \"uuid\": \"4f56f58d-1b0c-48f9-b3b6-c63020068760\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00002\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:21:55Z\"\n }\n },\n {\n \"uuid\": \"4fb86042-93ef-4209-88ca-8c287f16a2f6\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"00001\",\n \"created_at\": {\n \"$date\": \"2023-01-10T19:20:30Z\"\n }\n },\n {\n \"uuid\": \"3a6dc43d-bdb5-41b9-be93-15ab389380a9\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"New Docu \",\n \"created_at\": {\n \"$date\": \"2023-01-10T18:44:01Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"69b1dd00-8ecf-4ba3-8df4-2cbba3887505\",\n \"sender\": {\n \"$oid\": \"63adadf287e482e6f128ec0e\"\n },\n \"message\": \"88888888888888888888\",\n \"created_at\": {\n \"$date\": \"2023-01-10T16:01:22Z\"\n }\n },\n {\n \"uuid\": \"3ea03321-3c99-48b6-a7fd-2cc5fa514fb3\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"0000000000000\",\n \"created_at\": {\n \"$date\": \"2023-01-10T15:51:20Z\"\n }\n },\n {\n \"uuid\": \"c8e35012-1106-4e3f-b678-6040002d54b8\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"pppppp\",\n \"created_at\": {\n \"$date\": \"2023-01-10T15:40:24Z\"\n }\n }\n ]\n },\n {\n \"result\": [\n {\n \"uuid\": \"b78f1288-5363-4b0f-9bbe-ddf73f60fac1\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"Kio nn sass,,,\",\n \"created_at\": {\n \"$date\": \"2023-01-10T18:46:39Z\"\n }\n },\n {\n \"uuid\": \"94e3ae3a-eb2c-4ceb-b580-e97f4ec49aba\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"Kio nn sass,,,\",\n \"created_at\": {\n \"$date\": \"2023-01-10T18:44:57Z\"\n }\n },\n {\n \"uuid\": \"80c86174-9836-477b-b0d3-e4cb968b015a\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"Another messgee 2\",\n \"created_at\": {\n \"$date\": \"2023-01-10T18:44:45Z\"\n }\n },\n {\n \"uuid\": \"3a6dc43d-bdb5-41b9-be93-15ab389380a9\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"New Docu \",\n \"created_at\": {\n \"$date\": \"2023-01-10T18:44:01Z\"\n }\n },\n {\n \"uuid\": \"69b1dd00-8ecf-4ba3-8df4-2cbba3887505\",\n \"sender\": {\n \"$oid\": \"63adadf287e482e6f128ec0e\"\n },\n \"message\": \"i am fine thanks\",\n \"created_at\": {\n \"$date\": \"2023-01-10T16:01:22Z\"\n }\n },\n {\n \"uuid\": \"3ea03321-3c99-48b6-a7fd-2cc5fa514fb3\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"Buddy hhh.. \",\n \"created_at\": {\n \"$date\": \"2023-01-10T15:51:20Z\"\n }\n },\n {\n \"uuid\": \"c8e35012-1106-4e3f-b678-6040002d54b8\",\n \"sender\": {\n \"$oid\": \"63ad8631e0d6cfe452b80677\"\n },\n \"message\": \"LOL How are you \",\n \"created_at\": {\n \"$date\": \"2023-01-10T15:36:24Z\"\n }\n }\n ]\n }\n]\n$concatArray// MongoDB Playground\n// Use Ctrl+Space inside a snippet or a string literal to trigger completions.\n\nconst database = 'test3';\n\n// The current database to use.\nuse(database);\n\n// db.chats.find({\n// \"members\": {\n// \"$eq\": [\n// ObjectId('63ad8631e0d6cfe452b80677'),\n// ObjectId('63adadf287e482e6f128ec0e')\n// ]\n// }\n// }\n// )\n\n// db.chats.aggregate(\n// {\n// $match: {\n// \"members\": {\n// \"$all\": [\n// ObjectId('63ad8631e0d6cfe452b80677'),\n// // ObjectId('63adadf287e482e6f128ec0e'),\n// ObjectId('63b3c2b8ce51cf1fca0325ad')\n// ]\n// },\n// } \n// },\n// {\n// $sort: {\n// \"created_at\": -1\n// }\n// },\n// // {\n// // $project: {\n// // \"total\": 1,\n// // \"_id\": 0\n// // }\n// // },\n\n\n// {\n// $limit: 1\n// },\n// )\n// .sort({\"created_at\": -1})\n\n// db.chats.find(\n// {\n// \"members\": {\n// \"$all\": [\n// ObjectId('63ad8631e0d6cfe452b80677'),\n// ObjectId('63adadf287e482e6f128ec0e'),\n// // ObjectId('63b3c2b8ce51cf1fca0325ad')\n// ]\n// }\n// },\n// )\n\n// db.chats.find({\n// \"members\": {\n// \"$eq\": [\n// ObjectId('63ad8631e0d6cfe452b80677'),\n// ObjectId('63adadf287e482e6f128ec0e')\n// ]\n// }\n// }\n// )\n\n\ndb.chats.aggregate(\n {\n /**\n * query: The query in MQL.\n */\n $match: {\n \"members\": {\n \"$all\": [\n ObjectId('63ad8631e0d6cfe452b80677'),\n ObjectId('63adadf287e482e6f128ec0e'), \n ]\n }\n },\n },\n {\n /**\n * Provide any number of field/order pairs.\n */\n $sort: {\n \"created_at\": -1\n }\n },\n {\n /**\n * specifications: The fields to\n * include or exclude.\n */\n $project: {\n \"_id\": 0,\n // \"members\": 1,\n \"result\": {\n $sortArray: {input: \"$message\", sortBy: {created_at: -1}},\n }\n }\n },\n {\n /**\n * specifications: The fields to\n * include or exclude.\n */\n $project: {\n \"messages\": {\n '$concatArrays': [\n \"$result\", \"$result\"\n ]\n }\n }\n }\n)\nresultmessagesresult"}, {"role": "assistant", "content": "Text:i solved this\u2026 but is it performance friendly\nCode:\ndb.chats.aggregate(\n {\n /**\n * query: The query in MQL.\n */\n $match: {\n \"members\": {\n \"$all\": [\n ObjectId('63ad8631e0d6cfe452b80677'),\n ObjectId('63adadf287e482e6f128ec0e'), \n ]\n }\n },\n },\n {\n /**\n * Provide any number of field/order pairs.\n */\n $sort: {\n \"created_at\": -1\n }\n },\n // {\n // /**\n // * specifications: The fields to\n // * include or exclude.\n // */\n // $project: {\n // \"_id\": 0,\n // // \"members\": 1,\n // \"result\": {\n // $sortArray: {input: \"$message\", sortBy: {created_at: -1}},\n // // \"$initialValue\": {},\n // }\n // }\n // },\n {\n /**\n * path: Path to the array field.\n * includeArrayIndex: Optional name for index.\n * preserveNullAndEmptyArrays: Optional\n * toggle to unwind null and empty values.\n */\n $unwind: {\n path: \"$messages\",\n // includeArrayIndex: 'string',\n // preserveNullAndEmptyArrays: boolean\n }\n },\n {\n /**\n * specifications: The fields to\n * include or exclude.\n */\n $project: {\n \"_id\": 0,\n \"messages\": 1\n // \"members\": 1,\n // \"result\": {\n // $sortArray: {input: \"$message\", sortBy: {created_at: -1}}\n // }\n }\n },\n {\n /**\n * Provide any number of field/order pairs.\n */\n $sort: {\n \"messages.created_at\": -1\n }\n },\n {\n /**\n * outputFieldN: The first output field.\n * stageN: The first aggregation stage.\n */\n $facet: {\n data: [ \n {$skip: 0},\n {$limit: 2} \n ],\n pagination: [\n {$count: \"count\"}\n ]\n }\n }\n // {\n // /**\n // * Provide any number of field/order pairs.\n // */\n // $sort: {\n // \"created_at\": 1\n // }\n // }\n // {\n // $unwind: '$message',\n // }\n \n\n // {\n // /**\n // * specifications: The fields to\n // * include or exclude.\n // */\n // $project: {\n // \"result\": {\n // $sortArray: {input: \"$message\", sortBy: {created_at: -1}}\n // }\n\n // }\n // }\n)\n"}, {"role": "assistant", "content": "Text:if you allow me then I\u2019ll be the first beta tester of your chat schema design, which I used on my website page.\nCode:"}, {"role": "assistant", "content": "Text:Of course, you can use it. and if you can please improve it. thank you\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Change dbPath on Ubuntu and tags: ['containers']"}, {"role": "user", "content": "Text:Hello,I want to customise (change) the dbPath on ubuntu 20.04.The configuration file:/etc/mongod.confspecifies the data directory/dbPath:/var/lib/mongodbThe docs here: https://docs.mongodb.com/manual/reference/configuration-options/#storage.dbPathnote that on linux one can\u2019t simply change the dbPath in the config file:\" The Linux package init scripts do not expect storage.dbPath to change from the defaults. If you use the Linux packages and change storage.dbPath , you will have to use your own init scripts and disable the built-in scripts.\"Unfortunately, I haven\u2019t found any information on those init script(s), i.e. where I can find them, and what in them might need editing in order for the change of dbPath in the config. file to be allowed to work.Because I\u2019m using ubuntu the init system is systemctl, see here: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/Aside: why do I want to change the dbPath from its default? Because my laptop is dual boot and I have mongodb on both win10 and unbuntu, but want to be able to access the same database files\u2013i.e. access the win10 directory/data storage from within the mongodb on ubuntu. So I think I want to use something like:/media/[username]/[win10 partition name]/data/dbwhich corresponds to:C:\\data\\dbBut as the docs say, the init script(s) also need changing for that to work.Thanks for your help.\nCode:storage.dbPathstorage.dbPath"}, {"role": "assistant", "content": "Text:Changing the init script, if running systemd, is not that complicated.The commandsudo systemctl status mongodwill tell you the location of the script. On my system, it is /usr/lib/systemd/system/mongod.service. You will see in this text file some ExecStartPre= statement. You just have to match those directories and files to the one specified in your mongod.conf. You will see that these are probably only needed at the first start and it is too make sure that the directories exist and are writable by mongod user.But that\u2019s the theory. On a production server I do not mess with this. On a dev machine I start mongod manually with the config file I pleased. Sometimes I have different config files that point to different directories depending of the project. Just make sure directories exist and are writable by the user that starts mongod.\nCode:sudo systemctl status mongod"}, {"role": "assistant", "content": "Text:On top of what @steevej mentioned, you will also need to set the correct permissions on the directory. MongoDB in linux will need your new dbPath location to be writable by the mongod user. When you install MongoDB in Linux, the package will create the mongod user and group and then the /data/db path will be owned by this user/group. On a dual boot system, I don\u2019t know what will happen if you try to change the ownership of a path on a Windows mount. You might need to open the path up to be world read/writable (chmod 777 /media/[username]/[win10 partition name]/data/db).\nCode:dbPathmongodmongod/data/dbchmod 777 /media/[username]/[win10 partition name]/data/db"}, {"role": "user", "content": "Text:Thanks. Here\u2019s the result when I tried that:When I look inside the /lib/systemd/system/mongod.service file I see:It may just be my lack of knowledge about linux but I don\u2019t see the sort of statement your describe. There is the line:ExecStart=/usr/bin/mongod --config /etc/mongod.confbut that\u2019s the same config file I earlier wrote of wanting to be able to change\u2013but when I do so, mongod will not start.Is this line important?:EnvironmentFile=-/etc/default/mongodThe thing is, I don\u2019t know what the leading - is doing there. There\u2019s no file at:/etc/default/mongod\nCode:user@machine:~$ sudo systemctl status mongod\n[sudo] password for user: \n\u25cf mongod.service - MongoDB Database Server\n Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset>\n Active: active (running) since Wed 2020-06-03 18:28:28 NZST; 5h 5min ago\n Docs: https://docs.mongodb.org/manual\n Main PID: 902 (mongod)\n Memory: 209.8M\n CGroup: /system.slice/mongod.service\n \u2514\u2500902 /usr/bin/mongod --config /etc/mongod.conf\n\nJun 03 18:28:28 machine systemd[1]: Started MongoDB Database Server.\n[Unit]\nDescription=MongoDB Database Server\nDocumentation=https://docs.mongodb.org/manual\nAfter=network.target\n\n[Service]\nUser=mongodb\nGroup=mongodb\nEnvironmentFile=-/etc/default/mongod\nExecStart=/usr/bin/mongod --config /etc/mongod.conf\nPIDFile=/var/run/mongodb/mongod.pid\n# file size\nLimitFSIZE=infinity\n# cpu time\nLimitCPU=infinity\n# virtual memory size\nLimitAS=infinity\n# open files\nLimitNOFILE=64000\n# processes/threads\nLimitNPROC=64000\n# locked memory\nLimitMEMLOCK=infinity\n# total threads (user+kernel)\nTasksMax=infinity\nTasksAccounting=false\n\n# Recommended limits for for mongod as specified in\n# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings\n\n[Install]\nWantedBy=multi-user.target\n"}, {"role": "assistant", "content": "Text:Is this line important?:EnvironmentFile=-/etc/default/mongodThe thing is, I don\u2019t know what the leading - is doing there. There\u2019s no file at:/etc/default/mongodThe EnvironmentFile bit states that the service should look in the provided file for environment variables. The - in front of the file means to not error out if the file doesn\u2019t exist. You can read more about EnvironmentFile in the systemd man page.The first place that I would start is changing the the path in the MongoDB config file. You can find the location of that file by looking at the ExecStart line:ExecStart=/usr/bin/mongod --config /etc/mongod.confIn your case, the file is located at /etc/mongod.conf. Edit that file and change the strorage.dbPath location to the path you want. Save and exit from the file. After doing that run sudo systemctl restart mongod, check the status of the service with systemctl status mongod and verify if it\u2019s running. If it is you\u2019re all set. If it\u2019s not you need to check the MongoDB log file (default should be /var/log/mongodb/mongodb.log I believe) to see why the service failed.\nCode:EnvironmentFile-ExecStart/etc/mongod.confstrorage.dbPathsudo systemctl restart mongodsystemctl status mongod/var/log/mongodb/mongodb.log"}, {"role": "user", "content": "Text:Good point by both you (Doug) and Steeve, earlier. These are the current permissions for that dir:user@machine:~$ ls -l /media/[user name]/[win10 partition name]/data\ntotal 8\ndrwxrwxrwx 1 owner group 8192 Jun 3 15:43 dbSo I think that shows access permissions are not what\u2019s preventing mongod working if I change the config file\u2019s dbPath to that target dir.?Would seeing the status help? After changing the dbPath in the config file to my target dir when mongod is stopped, I then:NB, '\u2018user\u2019 and \u2018machine\u2019 are my placeholders.\nCode:user@machine~$ sudo service mongod start\nuser@machine:~$ sudo service mongod status\n\u25cf mongod.service - MongoDB Database Server\n Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor pres>\n Active: failed (Result: exit-code) since Thu 2020-06-04 01:37:16 NZST; 3>\n Docs: https://docs.mongodb.org/manual\n Process: 33255 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=>\n Main PID: 33255 (code=exited, status=100)\n\nJun 04 01:37:16 machine systemd[1]: Started MongoDB Database Server.\nJun 04 01:37:16 machine systemd[1]: mongod.service: Main process exited, c>\nJun 04 01:37:16 machine systemd[1]: mongod.service: Failed with result 'ex>\n"}, {"role": "assistant", "content": "Text:The next step is to look at the the log file to see why it the mongod process failed. The service status just states that the process failed, but the log file will give more information about why.\nCode:mongod"}, {"role": "user", "content": "Text:OK, thanks. Here\u2019s nearly the last bit from that log file:2020-06-04T01:37:16.571+1200 I CONTROL [initandlisten] options: { config: \u201c/etc/mongod.conf\u201d, net: { bindIp: \u201c127.0.0.1\u201d, port: 27017 }, processManagement: { timeZoneInfo: \u201c/usr/share/zoneinfo\u201d }, storage: { dbPath: \u201c/media/[user name]/[win10 partition name]/data/db\u201d, journal: { enabled: true } }, systemLog: { destination: \u201cfile\u201d, logAppend: true, path: \u201c/var/log/mongodb/mongod.log\u201d } }\n2020-06-04T01:37:16.572+1200 I STORAGE [initandlisten] exception in initAndListen: Location28596: Unable to determine status of lock file in the data directory /media/[user name]/[win10 partition name]/data/db: boost::filesystem::status: Permission denied: \u201c/media/[user name]/[win10 partition name]/data/db/mongod.lock\u201d, terminatingI don\u2019t think it\u2019s simply permissions on that file itself, though, as:user@machine:/media/[user name]/[win10 partition name]/data/db$ ls -l mongod.lock\n-rwxrwxrwx 2 owner group 0 Jun 3 15:43 mongod.lockIs the file ownership itself important? The owner is not mongodb but rather my user name, while mongodb is the owner for the corresponding file on my linux partition\u2019s default dbPath, i.e.:\n/var/lib/mongodb/mongod.lockuser@machine:/var/lib/mongodb$ ls -l mongod.lock\n-rw------- 1 mongodb mongodb 0 Jun 4 01:35 mongod.lockI tried changing the owner & group to mongodb but after that mongod still failed to start, with the log:2020-06-04T02:16:26.635+1200 I CONTROL [initandlisten] options: { config: \u201c/etc/mongod.conf\u201d, net: { bindIp: \u201c127.0.0.1\u201d, port: 27017 }, processManagement: { timeZoneInfo: \u201c/usr/share/zoneinfo\u201d }, storage: { dbPath: \u201c/media/[user name]/[win10 partition name]/data/db\u201d, journal: { enabled: true } }, systemLog: { destination: \u201cfile\u201d, logAppend: true, path: \u201c/var/log/mongodb/mongod.log\u201d } }\n2020-06-04T02:16:26.637+1200 I STORAGE [initandlisten] exception in initAndListen: Location28596: Unable to determine status of lock file in the data directory /media/[user name]/[win10 partition name]/data/db: boost::filesystem::status: Permission denied: \u201c/media/[user name]/[win10 partition name]/data/db/mongod.lock\u201d, terminatingedit: correction: my attempt to change the owner & group of the mongod.lock file in the target win10 partition actually failed, but I\u2019m still not sure whether file ownership is important given everyone has rw access?\nCode:"}, {"role": "assistant", "content": "Text:What are the permissions on the /media/[user]/[win10 partition]/data/db folder? My guess is they are wide open as well, but worth checking.MongoDB is trying to access the lock file but it can\u2019t because the permissions of the file are rw by the owner only. You could try removing the mongod.lock file to see if you can start the service in Linux. I am not sure how that would affect things when you go back to your Windows version however.I get what you\u2019re trying to do having MongoDB available no matter whether you boot into Windows or Linux, but I\u2019m not sure that\u2019s going to work well. If you have Windows 10 and enabled WSL this might work a little more smoothly as you\u2019d have the same permissions and owners between the two systems. Trying to get the permissions on the files correctly and in a way that doesn\u2019t affect the other OS might be more hassle than it\u2019s worth.A couple of options that might be a better choice:Unfortunately I don\u2019t have a dual boot Windows machine so I\u2019m not able to test things out to see what would be needed to make this work on your set up.\nCode:/media/[user]/[win10 partition]/data/dbrwmongod.lock"}, {"role": "assistant", "content": "Text:That would be the way to go.A couple of options that might be a better choice:The free tier is very nice for that sort of things because it is accessible everywhere. Since I switch from a laptop on the go and a desktop at home having my data no matter what.\nCode:"}, {"role": "assistant", "content": "Text:Boa Notie. ! Td BEm !\nEstou enfrentando o mesmo problema. Porem utilizamos o Oracle Linxu.\nCriamos um novo diretorio e alteramos o arquivode configura\u00e7\u00e3o para apontar para o novo caminhio.Revisamos todas as permiss\u00f5es do diretorio porem o erro acontece. Sabem o que poder.Unable to determine status of lock file in the data directory /media/[user name]/[win10 partition name]/data/db: boost::filesystem::status: Permission denied: \u201c/media/[user name]/[win10 partition name]/data/db/mongod.lock\u201d, terminatingI don\u2019t think it\u2019s simply permissions on that\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Djongo NotImplementedError: Database objects do not implement truth value testing or bool() and tags: ['python']"}, {"role": "user", "content": "Text:Python 3.10.2\nDjango==4.1.1\nPyMongo==4.2.0\ndjongo==1.3.6\nwhile running migrate\nNotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None\nReinstall pymongo pymongo==3.12.3 resolved this problem.\nCode:"}, {"role": "user", "content": "Text:I\u2019m using mongodb 6.0.1 Community,maybe should be wating for next version of djongo\nCode:"}, {"role": "assistant", "content": "Text:Welcome to the MongoDB Community @John_Wang !The Djongo open source project currently isn\u2019t very actively maintained, so I suspect you\u2019ll be waiting a long while for bug fixes. You might be able to find more advice via the community resources in the Djongo Readme: Djongo Questions and Discussions.Reinstall pymongo pymongo==3.12.3 resolved this problem.Djongo 1.3.6 was released in June 2021 almost six months before the PyMongo 4.0 driver, so presumably needs some updates for full compatibility. Thanks for sharing your workaround.Can you share more details on how you are trying to use MongoDB with Django? For example: are you trying to run everything (including Django admin UI) with MongoDB as a backend database?I would personally be inclined to use an official driver like PyMongo or Motor with one of the Python microframeworks. The Django core is designed around SQL and isn\u2019t a great fit for MongoDB at the moment. Alternatively, you could use a driver like PyMongo in your Django views but would still need a supported relational database for core Django admin features.Regards,\nStennie\nCode:"}, {"role": "assistant", "content": "Text:To address the original error:NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not NoneThis was an intentional minor breaking change we made in PyMongo 4.0 described here:Database.__bool__ raises NotImplementedError\u00b6\nDatabase now raises an error upon evaluating as a Boolean. Code like this:if database:\nCan be changed to this:if database is not None:\nYou must now explicitly compare with None.https://pymongo.readthedocs.io/en/stable/migrate-to-pymongo4.html#database-bool-raises-notimplementederrorThe full trackback of the exception will show which line needs to be changed.\nCode:Database.__bool__if database:if database is not None:"}, {"role": "assistant", "content": "Text:it\u2019s resolved\nafter\npip install pymongo==3.12.3\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Can't create a unique index that ignores nulls in MongoDB and tags: ['data-modeling', 'java']"}, {"role": "user", "content": "Text:MongoDB\u2019s semantics of null is not the same as the semantics of null in SQL databases. As a consequent, unique indexes in MongoDB will raise uniqueness violation error when more than one document has null for the field that has unique index. Furthermore, there appears to be no way to create a unique index where nulls are ignored.MongoDB seems to have adopted the null value semantics of Java where null is a literal value assigned to variables of reference type to indicate that it has no referent. Thus, in Java null == null is true.However in the database world, null could have many meanings including indicating that the value of an attribute is unknown. Since two unknowns cannot be compared, null == null should be null, i.e., it is unknown if two unknowns are the same. With this semantics, two null values in a unique index are never equal in that null==null is not true. Thus unique indexes will allow multiple null values.This is an issue in migrating SQL database to MongoDB.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Rafiul_Ahad ,You should have a look at sparse indexes and, for even more flexibility, partial indexes.Regards,\nJeff\nCode:"}, {"role": "user", "content": "Text:I did. And nothing worked so far.\nCode:"}, {"role": "user", "content": "Text:From indexing - Unique index in mongoDB 3.2 ignoring null values - Stack Overflow, the following works for unique index for field of type String with nulls\nIndexOptions indexOptions = new IndexOptions().unique(true).partialFilterExpression(Filters.eq(\u201cfieldName\u201d,Filters.eq(\u201c$type\u201d,\u201cstring\u201d)));\nbut the note says:\n\"Just a note from my testing for anyone else looking for the same solution: although this worked as a mechanism for enforcing uniqueness while allowing nulls, Mongo didn\u2019t use the index for lookup queries using the indexed field and using hint() to force it resulted in very slow performance\u2013 Pete S \"Apr 20, 2018 at 10:25\nCode:"}, {"role": "assistant", "content": "Text:Welcome to the MongoDB Community @Rafiul_Ahad!MongoDB\u2019s semantics of null is not the same as the semantics of null in SQL databases.Null values are a placeholder for unknown values in both cases, but semantics for comparison and indexing may differ depending on the databases you are comparing. For example, SQL Server used to (and may still) disallow multiple nulls in a unique index by default \u2013 you have to create a filtered unique index (analogous to a partial index in MongoDB).I think the most straightforward way to ignore null values for the purposes of a unique index would be to avoid serialising null property values. For example, if you are using the MongoDB Java driver\u2019s POJO support this happens by default (see Serialization Customization).For more information on null semantics in MongoDB, please refer to Query for Null or Missing Fields.I did. And nothing worked so far.It seems like you may have found an acceptable solution for your use case.If that isn\u2019t the case or you are looking for further advice on this topic, please provide some more information on your environment:Per the answer you referenced from Stack Overflow, you can also use a partialFilterExpression matching on type to index a subset of documents based on field type (eg those where the fieldName value is a string ). However, as mentioned in the Partial Index Query Coverage documentation a partial index filter will not be chosen by the query planner unless a query includes the same filters:MongoDB will not use the partial index for a query or sort operation if using the index results in an incomplete result set.To use the partial index, a query must contain the filter expression (or a modified filter expression that specifies a subset of the filter expression) as part of its query condition.Regards.\nStennie\nCode:nullnullnullnullpartialFilterExpressionfieldNamestring"}, {"role": "user", "content": "Text:Hi Stennie,\nThank your for your response.\nMy current workaround is just that, a workaround to be able to create unique indexes on fields that have nulls in them. Since it comes with a performance penalty, it is not acceptable.\nLet me get on the soapbox for a moment. Indexes are physical database constructs. They should never be seen by the application. Asking an application to include the filter used in the index in their query is not acceptable.\nWithout divulging much about what I am doing, let\u2019s say that an application is programmatically generating data for insertion into MongoDB or MySQL database. It is also translating queries from a high level language to database query language. For MongoDB, this application will have to deal with this MongoDB idiosyncrasy adding to the complexity of the code.\nTo answer your questions, I am using MongoDB server version 6.0.0 and the application is using MongoDB Java Sync driver version 4.7.1. Initially the unique indexes were created using the following option:\nIndexOptions indexOptions = new IndexOptions().unique(true);\nBut that caused uniqueness violation exception so I included the partialFilterExpression that I mentioned in this thread.\nThanks.\n-Rafiul\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Update a collection field based on another collection and tags: ['aggregation']"}, {"role": "user", "content": "Text:Hi,I need to update a collection field based on the values from another collection, For eg:\ncollection 1 - employee\nvalues\n{\"_id\":1,\u201cname\u201d:\u201caaa\u201d, \u201cdepartment\u201d:11}\n{\"_id\":2,\u201cname\u201d:\u201cbbb\u201d, \u201cdepartment\u201d:12}collection 2 - department\n{\"_id\":11,\u201cname\u201d:\u201cdept1\u201d}\n{\"_id\":12,\u201cname\u201d:\u201cdept2\u201dI need the result collection as\nvalues\n{\"_id\":1,\u201cname\u201d:\u201caaa\u201d, \u201cdepartment\u201d:{\"_id\":11,\u201cname\u201d:\u201cdept1\u201d}}\n{\"_id\":2,\u201cname\u201d:\u201cbbb\u201d, \u201cdepartment\u201d:{\"_id\":12,\u201cname\u201d:\u201cdept2\u201d}}Please let me know how can I update the existing column or create new column in the collection to get the result like the aboveThanks,\nCode:"}, {"role": "assistant", "content": "Text:To that sort of things, you use the aggregation framework. You can read about it https://docs.mongodb.com/manual/aggregation/. MongoDB University also offer the M121 course related to it.You will need a $lookup aggregation stage. Find more at https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/It is not clear if you want to add the field to the employee collection or if you want a third collection. If the latter, you can achieve that with $out stage. More at https://docs.mongodb.com/manual/reference/operator/aggregation/out/I recommend to go via $out even if the goal is to add the field in the first collection. This way you do not screw up existing data and it gives you the opportunity to verify the results and simply swap the collection when you are happy.I also recommend using Compass to develop the pipeline as it makes it easy to experiment. You can export the pipeline to your favorite programming language once you are done. This being said, I prefer to keep my pipeline in their natural json form in a file that I can reuse in the shell or in my favorite language.\nCode:"}, {"role": "assistant", "content": "Text:You can perform a join, but a join is based a particular equality or an expression. If _id in the second table, is 10 + _id in the first table, then the join might be possible.However, the piped value is returned as an array, therefore, the array needs to be \u2018unwinded\u2019 and then manipulated into the document you want.Finally, you need to push this data into a new collection, which is quite easy once you actually get the data.\nCode:"}, {"role": "assistant", "content": "Text:You can perform a join, but a join is based a particular equality or an expression. If _id in the second table, is 10 + _id in the first table, then the join might be possible.It is $lookup in MongoDB. Join are SQL. I really do not understand what you mean by if _id is 10+ in the first table. Could you please elaborate?However, the piped value is returned as an array, therefore, the array needs to be \u2018unwinded\u2019 and then manipulated into the document you want.The exact stage is called $unwind as documented in https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/and then manipulated into the document you want.Quite right, manipulated with $project and/or $addFields.And finallyFinally, you need to push this data into a new collection, which is quite easy once you actually get the data.That\u2019s the $out stage already mentioned.\nCode:"}, {"role": "assistant", "content": "Text:$lookup is the operator to perform a join, you\u2019re right.I really do not understand what you mean by if _id is 10+ in the first table. Could you please elaborate?A person wants to join the documents, but a person needs some sort of expression to actually compare one document with another. I thought the expression is -_id(document in coll 1) = 10 + _id(document in coll 2)\nCode:"}, {"role": "assistant", "content": "Text:The _id in collection 1 is not related at all to the _id of collection 2.What\u2019s related is the field \u201cdepartment\u201d in collection 1 and _id of collection 2.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: CORS issue with client side Realm GraphQL Endpoint and tags: ['graphql']"}, {"role": "user", "content": "Text:Hi everyone,First off - Kudos to the Realm team for building a great product. I am having a CORS issue when working with the GraphQL endpoint from the browser and hoping someone can lead me in the right direction. My issue is this: (apologies for the somewhat long explanation but I wanted to be as detailed as I could)I am using a custom JWT Authentication solution, so I currently maintain all tokens for identity etc already in my app. I am able to setup a Custom JWT Authentication Authentication provider and input the corresponding JWK URI successfully in the Realm dashboard. It works fine after testing.The problem I have is then trying to pass in the JWT in the header of the post request to Realm GraphQL endpoint https://realm.mongodb.com/api/client/v2.0/app//graphql from the browser using fetch. When I do so I get the below CORS error:Access to fetch at \u2018https://realm.mongodb.com/api/client/v2.0/app//graphql\u2019 from origin \u2018http://localhost:3000\u2019 has been blocked by CORS policy: Response to preflight request doesn\u2019t pass access control check: No \u2018Access-Control-Allow-Origin\u2019 header is present on the requested resource. If an opaque response serves your needs, set the request\u2019s mode to \u2018no-cors\u2019 to fetch the resource with CORS disabled.Please note that I am not currently using the realm-web package as I do not want to add an additional JWT token layer (realm-web maintains their own JWT token system in local storage) to my app that already has its own. I simply want to include the JWT token in the header of a fetch request to then have Realm verify against the JWK URI setup in the Realm dashboard. The docs here Authenticate GraphQL Requests make it seem like this is entirely possible as it notes that you can pass the custom JWT trough as a jwtTokenString header using a normal http request. However, I still get the CORS error when attempting this request.I have also tried whitelisting my http://localhost:3000 in the Realm dashboard under Manage > Settings > Allowed Request Origins. Still not able to get it to work.I was able to get several less than ideal workarounds working:Using another server as a proxy - since a node.js environment doesn\u2019t have these CORS restrictions I was able to pass the token through to another endpoint which fetched the Realm GraphQL endpoint from a server environment successfully. (Not great as that essentially creates 2 servers)I was able to use both the realm-web package and my own system to make a more complicated auth system in which the realm-web package gave me a Bearer token to use without any CORS issues. (Not ideal as that requires 2 token systems)Potential Solutions:\nI\u2019m not positive on why the error is happening but I believe it may have something to do with the following that someone on the Realm team would have more context on:Are the URLS whitelisted in Allowed Request Origins mapped to the approved URLS for CORS requests?\nIs the Access-Control-Allow-Headers option on the wherever the Realm server is hosted allowing a header of jwtTokenString ?Really appreciate anyone who can help lead me in the right direction on this.Thank you!\nCode:jwtTokenStringjwtTokenString"}, {"role": "assistant", "content": "Text:Hi @Matt_Cunningham,Are you certain you use a PSOT method to run a qraphql query?Using an HTTPs API to run the query should be done via a POST method as defined here:Also you can use the Bearer method with an Access token you get from your JWT provider.I have noticed those CORS issues when trying to use other HTTP methods like \u201cGET\u201d.Best regards,\nPavel\nCode:"}, {"role": "user", "content": "Text:Hi @Pavel_Duchovny thanks for the reply, yes I am using a POST request and I am confident I am running the right query because it works in a server environment. When I switch to the browser with the same query it gives CORS issues. I am using something like this, passing in the JWT as jwtTokenString shown here Custom JWTAnother interesting note, I found these docs Authenticate HTTP Client Requests which statesMongoDB Realm enforces non-sync rules and sync rules for all client operations. This means that requests must be made by a logged in user of your Realm app.And those docs also offer the ability to get a Client API Access Token through the login endpoint.But I am curious what that means - does that mean I must use the realm-web package or ping the Realm login endpoint to receive a Realm generated Bearer token?In my case I am still wondering if I am able to just provide my custom JWT along with all of my requests to the endpoint and not have to generate another Bearer token through the login endpoint or realm-web package. Does that make sense?\nCode:jwtTokenString const result = await fetch(\n `https://myrealmgraphqlendpoint`,\n {\n method: \"POST\",\n headers: {\n jwtTokenString: user.token,\n },\n body: JSON.stringify({ query: FIND_MOVIES }),\n }\n );\n const json = await result.json();\n console.log(json);\n"}, {"role": "assistant", "content": "Text:Hi @Matt_Cunningham,I think it should work both ways otherwise it might be a bug.You should be able to provide credentials to do both auth + query. It can be email/password but also jwt token.Out of curiosity does a bearer token with access token doesn\u2019t yield cors errors?Best\nPavel\nCode:"}, {"role": "user", "content": "Text:@Pavel_Duchovny Yeah I think it may be a bug. So I tried using Bearer with my JWT from my provider (not one assigned from Realm) like so:But now I get the below error in the console, which is probably because the Bearer strategy on the Realm endpoint is expecting a Realm assigned token format, not custom JWT format which maybe is why the jwtTokenString header exists in the first place.If it is a bug, I am happy to write out any further steps to reproduce. Let me know!\nCode: const result = await fetch(\n `https://myrealmgraphqlendpoint`,\n {\n method: \"POST\",\n headers: {\n Authorization: \"Bearer \" + user.token, \n },\n body: JSON.stringify({ query: FIND_MOVIES }),\n }\n );\njwtTokenString{\n \"error\": \"value of 'kid' has invalid format\",\n \"link\": \"https://realm.mongodb.com/groups/5f3ab9628951c83aa903a0b0/apps/5f5d28bcdda1ce73d48eaa42/logs?co_id=5f5f9cb6a93317dab797e984\"\n}\n"}, {"role": "assistant", "content": "Text:@Matt_Cunningham,The bearer token can\u2019t be your custom one but only realms.I asked you to test it in 2 steps get a realm access token from custom-jwt/login endpoint and use it in the bearer.Pavel\nCode:"}, {"role": "user", "content": "Text:Hi @Pavel_Duchovny,The 2 steps process works when I use the login endpoint - the login endpoint responds with an access_token and refresh_token etc. Using the provided access_token I am able to to query using the Bearer method successfully. While that process works and gives no CORS errors, it would mean I have to deal with handling refreshes of my own custom JWTs as well as the access_token that is provided back in the payload from the Realm login endpoint. Sorry if I am being repetitive here, but as you mentioned in your earlier replyYou should be able to provide credentials to do both auth + query. It can be email/password but also jwt token.Which means there should be a scenario where I wouldn\u2019t have to use the login endpoint at all correct?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Pavel_Duchovny,I\u2019m facing the same problem. I\u2019m using an apiKey header and I\u2019m getting the same error @Matt_Cunningham is getting.The thing is when I try the endpoint using Postman it works but when I use Apollo client with Angular it does not!!I hope that you have any idea about whats happening. \nCode:"}, {"role": "assistant", "content": "Text:Hey Hadi -I\u2019m assuming you\u2019re running into this error because you\u2019re calling it from the browser. Please consider using authorization headers https://docs.mongodb.com/realm/graphql/authenticate/#credential-headers\nCode:"}, {"role": "assistant", "content": "Text:me too, having the same error\nfrom browser\nwith apiKey or authorization, getting CORS error\ni added on App Settings > Allowed request origin: localhost but not worked too\nCode:"}, {"role": "assistant", "content": "Text:HiIs there an update for solution on this? Perhaps an example of how to update the apiKey header?Many thanks!\nCode:"}, {"role": "assistant", "content": "Text:The API key shouldn\u2019t be used directly in the browser. Please authenticate with the API token like so.and then use the access token to authenticate to GQL as Pavel mentioned\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m unable to get past CORS error (Access to fetch at \u2026 from origin \u2026 has been blocked by CORS policy: Response to preflight request doesn\u2019t pass access control check: No \u2018Access-Control-Allow-Origin\u2019 header is present\u2026) using the browser to query the GQL endpoint. I am passing the bearer token issued by the login endpoint and the POST request works fine in Postman, including receiving the required \u2018Access-Control-Allow-Origin\u2019.However, in the browser, the request first sends the OPTIONS request to verify CORS, and the response from the server does not contain the requisite \u201cAccess-Control-Allow-Origin\u201d. I can duplicate this result in Postman as well by setting the request type to OPTIONS and including all of the necessary header variables (access-control-request-headers, access-control-request-method, etc.). Any thoughts on what I might be missing?\nCode:"}, {"role": "assistant", "content": "Text:Eric, can you paste the full request that you\u2019re sending to Realm (including all the headers, body, etc)?We display an example of how to use Apollo Client with GraphQL here if you\u2019re using GraphQL in the browser - realm-graphql-apollo-react/index.js at master \u00b7 mongodb-university/realm-graphql-apollo-react \u00b7 GitHub\nCode:"}, {"role": "assistant", "content": "Text:\nUnacceptable.\nAWS, here we come\nCode:"}, {"role": "assistant", "content": "Text:G\u2019Day, @Jason_Steele,I acknowledge your frustration Is there something we can help you with? Could you please share your use case and what you are looking for?Could we discuss a win-win solution for you and us? Cheers, \nCode:"}, {"role": "assistant", "content": "Text:I\u2019m having the same issue, but with Vue 3 not React and trying to use a apiKey. I\u2019m trying to find code examples of how to get it to work but i\u2019m not finding anything. Is there any examples for realm-graphql-apollo-vue3?\nCode:"}, {"role": "assistant", "content": "Text:Hi guys! I am currently considering a Mongodb Atlas stack, but this issue looks like a deal breaker:This is a token example:This is the JWKs URI: https://beez-monitor.eu.auth0.com/.well-known/jwks.jsonMy app is https://eu-central-1.aws.data.mongodb-api.com/app/beez-app-loehxIs there a workaround, or am I doing something wrong?\nCode:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IldvTmpxMlR5dzZJWWhlR0FhblFHTyJ9.eyJpc3MiOiJodHRwczovL2JlZXotbW9uaXRvci5ldS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NjQ2Y2MyYWI2NjdkY2JjODk3ZjYyNzEyIiwiYXVkIjoiYmVlei1hcHAtbG9laHgiLCJpYXQiOjE2ODUxODY2OTUsImV4cCI6MTY4NTI3MzA5NSwiYXpwIjoiMXBuT1o3OFRybXlkSU1yMENMZGE2Q01GS1FQVkpqZ0QifQ\n"}, {"role": "assistant", "content": "Text:Never mind, figured it out: as @Pavel_Duchovny mentioned, I cannot use my custom JWT from Auth0, I need to exchange it first for a Mongodb Realm token, by making a request to https://eu-central-1.aws.realm.mongodb.com/api/client/v2.0/app/app-name-here/auth/providers/custom-token/login with the payload {\u201ctoken\u201d:} \u2013 this is sort of documented here: https://www.mongodb.com/docs/atlas/app-services/users/sessions/#authenticate-a-userYou guys could save the world a lot of time spent troubleshooting this if you would:(either of them would do )\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Job for mongod.service failed because the control process exited with error code. See \"systemctl status mongod.service\" and \"journalctl -xe\" for details and tags: []"}, {"role": "user", "content": "Text:i am on centos 7 when i trying to run sudo service mongod start i got an error like this\nCode:sudo service mongod startJob for mongod.service failed because the control process exited with error code. See \"systemctl status mongod.service\" and \"journalctl -xe\" for details.\n"}, {"role": "assistant", "content": "Text:The first thing to do when you get an error message that saysSee \"systemctl status mongod.service\" and \"journalctl -xe\" for details.is to see \u201csystemctl status mongod.service\u201d and \u201cjournalctl -xe\u201d for details.Even us, we cannot help you without the details.\nCode:See \"systemctl status mongod.service\" and \"journalctl -xe\" for details."}, {"role": "assistant", "content": "Text:Any news on the details? If you were able to fix your issue by following the advice, please mark my post as the solution so that others follow your steps.\nCode:"}, {"role": "assistant", "content": "Text:@Brijesh_Kalkani, please follow up on your post. Did you follow the tip I provided in my post? Did it help you find a solution? If so please mark it as the solution. This will help this forum to be efficient.\nCode:"}, {"role": "assistant", "content": "Text:Hi,\nyou can see what are the errors, by typing in the shell:\nsystemctl status mongod.service\njournactl -xe\ntail -f /path/to/log_file/mongod.logRegards\nCode:"}, {"role": "assistant", "content": "Text:I had the same error as OP and this is the output of journactl -xe:\nCode:journactl -xeJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU5: Core temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU1: Core temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU1: Package temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU5: Package temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU0: Package temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU6: Package temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU4: Package temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU2: Package temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU7: Package temperature/speed normal\nJan 18 15:31:33 rylan-ThinkPad-E590 kernel: CPU3: Package temperature/speed normal\nJan 18 15:31:38 rylan-ThinkPad-E590 slack.desktop[14549]: [01/18/22, 15:31:38:424] info: [RTM] (T2BRHD5EC) Processed 1 user_typing event(s) in channel(s) D02F5BU9B18 over 6.70ms\nJan 18 15:31:43 rylan-ThinkPad-E590 slack.desktop[14549]: [01/18/22, 15:31:43:710] info: [MSG-SHARED-RTM] (TC98Y5AQ3) dispatch to single store 1 msgs\nJan 18 15:31:43 rylan-ThinkPad-E590 slack.desktop[14549]: [01/18/22, 15:31:43:719] warn: (TC98Y5AQ3) Notification (message) suppressed because:\nJan 18 15:31:43 rylan-ThinkPad-E590 slack.desktop[14549]: Channel is muted\nJan 18 15:31:43 rylan-ThinkPad-E590 slack.desktop[14549]: [01/18/22, 15:31:43:720] info: [RTM] (TC98Y5AQ3) Processed 1 message:bot_message event(s) in channel(s) D02D5RQ95LL over 21.60ms\nJan 18 15:31:43 rylan-ThinkPad-E590 slack.desktop[14549]: [01/18/22, 15:31:43:780] info: [COUNTS] (TC98Y5AQ3) Updated unread_cnt for D02D5RQ95LL: 894\nJan 18 15:31:43 rylan-ThinkPad-E590 slack.desktop[14549]: [01/18/22, 15:31:43:943] info: [RTM] (T2BRHD5EC) Processed 1 user_typing event(s) in channel(s) D02F5BU9B18 over 7.30ms\nJan 18 15:31:46 rylan-ThinkPad-E590 sudo[13424]: rylan : TTY=pts/1 ; PWD=/home/rylan/Documents/physics-benchmarking-neurips2021/experiments/dominoes_redyellow_pilot ; USER=root ; COMMAND=/bin/systemctl start \nJan 18 15:31:46 rylan-ThinkPad-E590 sudo[13424]: pam_unix(sudo:session): session opened for user root by (uid=0)\nJan 18 15:31:46 rylan-ThinkPad-E590 systemd[1]: Starting LSB: An object/document-oriented database...\n-- Subject: Unit mongodb.service has begun start-up\n-- Defined-By: systemd\n-- Support: http://www.ubuntu.com/support\n-- \n-- Unit mongodb.service has begun starting up.\nJan 18 15:31:46 rylan-ThinkPad-E590 mongodb[13427]: * Starting database mongodb\nJan 18 15:31:47 rylan-ThinkPad-E590 mongodb[13427]: ...fail!\nJan 18 15:31:47 rylan-ThinkPad-E590 systemd[1]: mongodb.service: Control process exited, code=exited status=1\nJan 18 15:31:47 rylan-ThinkPad-E590 systemd[1]: mongodb.service: Failed with result 'exit-code'.\nJan 18 15:31:47 rylan-ThinkPad-E590 systemd[1]: Failed to start LSB: An object/document-oriented database.\n-- Subject: Unit mongodb.service has failed\n-- Defined-By: systemd\n-- Support: http://www.ubuntu.com/support\n-- \n-- Unit mongodb.service has failed.\n\n"}, {"role": "assistant", "content": "Text:This is my output from looking at the first few lines of /var/log/mongodb/mongodb.log:\nCode:/var/log/mongodb/mongodb.log2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] MongoDB starting : pid=6332 port=27017 dbpath=/var/lib/mongodb 64-bit host=rylan-ThinkPad-E590\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] db version v3.6.3\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] git version: 9586e557d54ef70f9ca4b43c26892cd55257e1a5\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.1.1 11 Sep 2018\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] allocator: tcmalloc\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] modules: none\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] build environment:\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] distarch: x86_64\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] target_arch: x86_64\n2022-01-18T15:21:05.419-0800 I CONTROL [initandlisten] options: { config: \"/etc/mongodb.conf\", net: { bindIp: \"127.0.0.1\", unixDomainSocket: { pathPrefix: \"/run/mongodb\" } }, storage: { dbPath: \"/var/lib/mongodb\", journal: { enabled: true } }, systemLog: { destination: \"file\", logAppend: true, path: \"/var/log/mongodb/mongodb.log\" } }\n2022-01-18T15:21:05.420-0800 I STORAGE [initandlisten]\n2022-01-18T15:21:05.420-0800 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine\n2022-01-18T15:21:05.420-0800 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem\n2022-01-18T15:21:05.420-0800 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=7429M,session_max=20000,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),statistics_log=(wait=0),verbose=(recovery_progress),\n2022-01-18T15:21:06.112-0800 I CONTROL [initandlisten]\n2022-01-18T15:21:06.112-0800 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.\n2022-01-18T15:21:06.112-0800 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.\n2022-01-18T15:21:06.112-0800 I CONTROL [initandlisten]\n2022-01-18T15:21:06.113-0800 I STORAGE [initandlisten] createCollection: admin.system.version with provided UUID: 59618846-6a71-4606-b435-ec583269d327\n2022-01-18T15:21:06.120-0800 I COMMAND [initandlisten] setting featureCompatibilityVersion to 3.6\n2022-01-18T15:21:06.124-0800 I STORAGE [initandlisten] createCollection: local.startup_log with generated UUID: c5e16804-4ad9-4bf1-93e7-0282622efc94\n2022-01-18T15:21:06.130-0800 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/var/lib/mongodb/diagnostic.data'\n2022-01-18T15:21:06.130-0800 I NETWORK [initandlisten] waiting for connections on port 27017\n2022-01-18T15:22:27.230-0800 I CONTROL [signalProcessingThread] got signal 15 (Terminated), will terminate after current cmd ends\n2022-01-18T15:22:27.231-0800 I NETWORK [signalProcessingThread] shutdown: going to close listening sockets...\n2022-01-18T15:22:27.231-0800 I NETWORK [signalProcessingThread] removing socket file: /run/mongodb/mongodb-27017.sock\n2022-01-18T15:22:27.231-0800 I FTDC [signalProcessingThread] Shutting down full-time diagnostic data capture\n2022-01-18T15:22:27.232-0800 I STORAGE [signalProcessingThread] WiredTigerKVEngine shutting down\n2022-01-18T15:22:27.340-0800 I STORAGE [signalProcessingThread] shutdown: removing fs lock...\n2022-01-18T15:22:27.340-0800 I CONTROL [signalProcessingThread] now exiting\n2022-01-18T15:22:27.340-0800 I CONTROL [signalProcessingThread] shutting down with code:0\n"}, {"role": "assistant", "content": "Text:Hey there!\nThis is what i got. Could you help me out here?\nimage919\u00d7153 19 KB\n\nCode:"}, {"role": "assistant", "content": "Text:The first thing to do is to look at the log.\nCode:"}, {"role": "assistant", "content": "Text:I could see that the logs folder from /var/log was deleted and this caused the db to shut down.\nThe below steps resolved the issue -\n- switch to root user \u201csudo su\u201d\n- cd /var/log/\n- mkdir mongodb\n- chown -R mongod:mongod mongodb\n- systemctl start mongod.service\nCode:"}, {"role": "assistant", "content": "Text:Hi Steeve,I\u2019m again facing issues with MongoDB. This time its a different error. I think its the space issue.\nimage1364\u00d7670 174 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Check free space on your /var/log mount point\ndf -k /var/log\ndf -i /var/log\nClean unnecessary files\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Find cause of write conflict and tags: ['java', 'transactions']"}, {"role": "user", "content": "Text:This is using the reactive java driver: On my local dev machine I just saw the following error:`com.mongodb.MongoCommandException: Command failed with error 112 (WriteConflict): \u2018WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.\u2019 on server 127.0.0.1:27017.The full response is:{\u201cerrorLabels\u201d: [\u201cTransientTransactionError\u201d], \u201coperationTime\u201d: {\"$timestamp\": {\u201ct\u201d: 1602354840, \u201ci\u201d: 5}}, \u201cok\u201d: 0.0, \u201cerrmsg\u201d: \u201cWriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.\u201d, \u201ccode\u201d: 112, \u201ccodeName\u201d: \u201cWriteConflict\u201d, \u201c$clusterTime\u201d: {\u201cclusterTime\u201d: {\"$timestamp\": {\u201ct\u201d: 1602354840, \u201ci\u201d: 5}}, \u201csignature\u201d: {\u201chash\u201d: {\"$binary\": \u201cAAAAAAAAAAAAAAAAAAAAAAAAAAA=\u201d, \u201c$type\u201d: \u201c00\u201d}, \u201ckeyId\u201d: {\"$numberLong\": \u201c0\u201d}}}}`I also checked the MongoDB log, but there wasn\u2019t a single entry at the timestamp when the transaction failed. Is there any way to find out which query has caused the transaction to fail?\nCode:"}, {"role": "assistant", "content": "Text:What is the write concern for your write operation(s)?\nCode:"}, {"role": "user", "content": "Text:write concernWriteConcern is the default - w: 1 afaik\nCode:"}, {"role": "assistant", "content": "Text:Just because it\u2019s easier than thinking, can you try \u201cmajority\u201d?\nCode:"}, {"role": "user", "content": "Text:umm, just out of curiosity: why would that change anything if the driver only connects to a single node replica set?However, I can unfortunately not try that easily, because I haven\u2019t seen that exception ever since. Tried to replicate, doing the same things, but it never showed up again so far.Our web clients (browser) connect to a web socket, which modifies the current user. There is a chance that this operation took place when a transaction (which also modifies the user document) was still running. Just a vague guess, but I haven\u2019t found anything how I could check if this really is what has happened.\nCode:"}, {"role": "assistant", "content": "Text:Hi @st-h \u2026I was looking for easy first debugging steps, thinking along the lines of \u201cIf this happens a lot maybe it\u2019s the volume of writes and there\u2019s an inconsistency \u2026\u201dBut what you say \u2026 that there exists the possibility of a transaction interfering with another write \u2026 well, if you know that\u2019s a possibility in your application, it certainly sounds like the first thing to look at.Perhaps your code should handle exceptions and retry writes a few times in these instances.\nCode:"}, {"role": "user", "content": "Text:thanks for your reply. It\u2019s not happening a lot. I observed it running the full stack on my local machine, with me being the only active user (that\u2019s why I am worried about it). I am used to being able to lookup what the cause of an aborted transaction is due to using mysql before. It\u2019s quite a surprise to find out this seems to not be possible at all with MongoDB.Do you by any chance know more details about how the java drivers handle transactions? I asked a related question quite a while ago (without any replies), as there is nothing mentioned in the docs: How to efficiently handle transactions with the reactive java driver / clarifications on apiHowever, the main issue here is that I would like to confirm if my suspicion is accurate - however, it seems that\u2019s currently not possible at all - as there seems to be no way to find out why exactly a transaction failed?\nCode:"}, {"role": "assistant", "content": "Text:@st-h I do no know more details about the Java drivers or how to find the cause of an aborted transaction.It\u2019s quite a surprise to find out this seems to not be possible at all with MongoDB.Yes, I ran into a similar frustration. I had 3 tables to which I added validation. 2 worked; 1 did not. I searched and determined definitively there\u2019s no way to cause MongoDB to log why a validation failed. There\u2019s an open issue to add that feature.\nEdit: I did figure out my problem after exhaustive trial-and-error \u2026 a misspelling in one place My takeaway is that, as good as MongoDB is, and I like it and use it daily, it\u2019s not really \u201centerprise-ready\u201d. It doesn\u2019t have the completeness and stability of the mature relational products.\nCode:"}, {"role": "assistant", "content": "Text:This might give a better insight:Transactions are new in MongoDB but have been existed in SQL databases for more than 30 years. Transactions are used to maintain\u2026\nReading time: 5 min read\n\nCode:"}, {"role": "assistant", "content": "Text:Hi, may I know if you found a solution to the WriteConflict error?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Failed to unlink socket file: Operation not permitted and tags: []"}, {"role": "user", "content": "Text:I am facing this issue where I am unable to get my mongod started successfully:This is the error:{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.922+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cNETWORK\u201d, \u201cid\u201d:4915701, \u201cctx\u201d:\"-\",\u201cmsg\u201d:\u201cInitialized wire\nspecification\u201d,\u201cattr\u201d:{\u201cspec\u201d:{\u201cincomingExternalClient\u201d:{\u201cminWireVersion\u201d:0,\u201cmaxWireVersion\u201d:17},\u201cincomingInternalClient\u201d:{\u201cminWireVersion\u201d:0,\u201cmaxWireVersion\u201d:17},\u201coutgoing\u201d:{\u201cminWireVersion\u201d:6,\u201cmaxWireVersion\u201d:17},\u201cisInternalClient\u201d:true}}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.922+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:23285, \u201cctx\u201d:\"-\",\u201cmsg\u201d:\u201cAutomatically disabling\nTLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols\n\u2018none\u2019\u201d} {\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.924+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cNETWORK\u201d, \u201cid\u201d:4648601, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cImplicit TCP\nFastOpen unavailable. If TCP FastOpen is required, set\ntcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize.\u201d}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cREPL\u201d,\n\u201cid\u201d:5123008, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cSuccessfully registered\nPrimaryOnlyService\u201d,\u201cattr\u201d:{\u201cservice\u201d:\u201cTenantMigrationDonorService\u201d,\u201cnamespace\u201d:\u201cconfig.tenantMigrationDonors\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cREPL\u201d,\n\u201cid\u201d:5123008, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cSuccessfully registered\nPrimaryOnlyService\u201d,\u201cattr\u201d:{\u201cservice\u201d:\u201cTenantMigrationRecipientService\u201d,\u201cnamespace\u201d:\u201cconfig.tenantMigrationRecipients\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cREPL\u201d,\n\u201cid\u201d:5123008, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cSuccessfully registered\nPrimaryOnlyService\u201d,\u201cattr\u201d:{\u201cservice\u201d:\u201cShardSplitDonorService\u201d,\u201cnamespace\u201d:\u201cconfig.tenantSplitDonors\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:5945603, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cMulti threading\ninitialized\u201d} {\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:4615611, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cMongoDB\nstarting\u201d,\u201cattr\u201d:{\u201cpid\u201d:24280,\u201cport\u201d:27017,\u201cdbPath\u201d:\"/data/db\",\u201carchitecture\u201d:\u201c64-bit\u201d,\u201chost\u201d:\u201cehsan-HP\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:23403, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cBuild\nInfo\u201d,\u201cattr\u201d:{\u201cbuildInfo\u201d:{\u201cversion\u201d:\u201c6.0.3\u201d,\u201cgitVersion\u201d:\u201cf803681c3ae19817d31958965850193de067c516\u201d,\u201copenSSLVersion\u201d:\u201cOpenSSL\n1.1.1 11 Sep 2018\u201d,\u201cmodules\u201d:,\u201callocator\u201d:\u201ctcmalloc\u201d,\u201cenvironment\u201d:{\u201cdistmod\u201d:\u201cubuntu1804\u201d,\u201cdistarch\u201d:\u201cx86_64\u201d,\u201ctarget_arch\u201d:\u201cx86_64\u201d}}}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:51765, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cOperating\nSystem\u201d,\u201cattr\u201d:{\u201cos\u201d:{\u201cname\u201d:\u201cUbuntu\u201d,\u201cversion\u201d:\u201c18.04\u201d}}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.925+05:00\u201d},\u201cs\u201d:\u201cI\u201d,\n\u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:21951, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cOptions set\nby command line\u201d,\u201cattr\u201d:{\u201coptions\u201d:{}}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.926+05:00\u201d},\u201cs\u201d:\u201cE\u201d,\n\u201cc\u201d:\u201cNETWORK\u201d, \u201cid\u201d:23024, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cFailed to\nunlink socket\nfile\u201d,\u201cattr\u201d:{\u201cpath\u201d:\"/tmp/mongodb-27017.sock\",\u201cerror\u201d:\u201cOperation not\npermitted\u201d}} {\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.926+05:00\u201d},\u201cs\u201d:\u201cF\u201d,\n\u201cc\u201d:\u201cASSERT\u201d, \u201cid\u201d:23091, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cFatal\nassertion\u201d,\u201cattr\u201d:{\u201cmsgid\u201d:40486,\u201cfile\u201d:\u201csrc/mongo/transport/transport_layer_asio.cpp\u201d,\u201cline\u201d:1125}}\n{\u201ct\u201d:{\"$date\":\u201c2023-01-13T12:33:59.926+05:00\u201d},\u201cs\u201d:\u201cF\u201d, \u201cc\u201d:\u201cASSERT\u201d,\n\u201cid\u201d:23092, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\"\\n\\n***aborting after\nfassert() failure\\n\\n\"}What I have tried so far:Delete /tmp/mongodb-27017.sock file and then start mongod by doing sudo service mongod start. It didn\u2019t work. The file mongodb-27017.sock created after running this comand has the following permissions:These are the permissions of /data/db:What is going wrong here? This is my mongod version:I am on Ubuntu 18.EDIT:\nHere are the contents of /var/log/auth.log:\nCode:mongod/tmp/mongodb-27017.sockmongodsudo service mongod startmongodb-27017.socksrwx------ 1 mongodb mongodb 0 January 13 12:49 /tmp/mongodb-27017.sock\n/data/db$ ls -la /data/db\ntotal 8\ndrwxr-xr-x 2 mongodb mongodb 4096 January 13 11:35 .\ndrwxr-xr-x 3 root root 4096 January 13 11:35 ..\nmongod$ mongod --version\ndb version v6.0.3\nBuild Info: {\n \"version\": \"6.0.3\",\n \"gitVersion\": \"f803681c3ae19817d31958965850193de067c516\",\n \"openSSLVersion\": \"OpenSSL 1.1.1 11 Sep 2018\",\n \"modules\": [],\n \"allocator\": \"tcmalloc\",\n \"environment\": {\n \"distmod\": \"ubuntu1804\",\n \"distarch\": \"x86_64\",\n \"target_arch\": \"x86_64\"\n }\n}\nUbuntu 18/var/log/auth.logJan 13 13:40:24 ehsan-HP sudo: ehsan : TTY=pts/7 ; PWD=/home/ehsan ; USER=root ; COMMAND=/usr/sbin/service mongod restart\nJan 13 13:40:24 ehsan-HP sudo: pam_unix(sudo:session): session opened for user root by (uid=0)\nJan 13 13:40:24 ehsan-HP sudo: pam_unix(sudo:session): session closed for user root"}, {"role": "assistant", "content": "Text:Appears to be permissions issue when you try to bring up mongod as different users\nHow did you start mongod first time?\nMost likely you issued just mongod\nAfter removing tmp file try bring up mongod by issuing just mongod\nYou should not use sudo which will try to create files as root\nPlease check documentation\nIf you installed mongod as service you have to use sudo sysctl mongod start\nCode:"}, {"role": "assistant", "content": "Text:im facing the same isssue\nCode:"}, {"role": "assistant", "content": "Text:run,or, check the ownership of the above\nCode:rm -f /tmp/mongodb-27017.sock\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: pymongo.errors.ServerSelectionTimeoutError with atlas even when added to network access and tags: ['python', 'connecting', 'atlas-cluster']"}, {"role": "user", "content": "Text:Hello, I have been using pymongo with atlas for a while now, and suddenly around two hours ago, I must have done something wrong because the same code I\u2019ve been using the entire time suddenly stopped working.I have attempted to isolate the issue and made this reproducible exampleand this is the full tracebackThe same error is raised even for other operations.I have attempted to search around for a solution. Most of them consisted of using different parameters for the client or adding parameters to the query of the connection string, all of which yield the same result.I have of course added both my IP and 0.0.0.0 to the network access.\nimage1447\u00d7208 18.8 KBVersions:Any directions would be appreciated, I can always provide more info.\nCode:from pymongo import MongoClient\n\nclient = MongoClient(\n \"mongodb+srv://culturebot:[pass]@cluster0.whzdc.mongodb.net/culturebot?retryWrites=true&w=majority\"\n)\nprint(client.list_database_names())\nTraceback (most recent call last):\n File \"C:\\Users\\D\\code\\thesadru\\culturebot\\_.py\", line 6, in \n print(client.list_database_names())\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\mongo_client.py\", line 1918, in list_database_names\n for doc in self.list_databases(session, nameOnly=True)]\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\mongo_client.py\", line 1899, in list_databases\n res = admin._retryable_read_command(cmd, session=session)\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\database.py\", line 755, in _retryable_read_command\n return self.__client._retryable_read(\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\mongo_client.py\", line 1460, in _retryable_read\n server = self._select_server(\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\mongo_client.py\", line 1278, in _select_serverer\n server = topology.select_server(server_selector)\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\topology.py\", line 241, in select_server\n return random.choice(self.select_servers(selector,\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\topology.py\", line 199, in select_servers\n server_descriptions = self._select_servers_loop(\n File \"C:\\Users\\D\\AppData\\Roaming\\Python\\Python39\\site-packages\\pymongo\\topology.py\", line 215, in _select_servers_loop\n raise ServerSelectionTimeoutError(\npymongo.errors.ServerSelectionTimeoutError: cluster0-shard-00-02.whzdc.mongodb.net:27017: timed out,cluster0-shard-00-00.whzdc.mongodb.net:27017: timed out,cluster0-shard-00-01.whzdc.mongodb.net:27017: timed out, Timeout: 30s, Topology Description: , , ]>\n0.0.0.0"}, {"role": "assistant", "content": "Text:This error means that pymongo timed out while waiting for a response from the remote server. Usually this means there is a network issue between your machine and the database.\nCode:NetworkTimeout('cluster0-shard-00-01.whzdc.mongodb.net:27017: timed out')\npip listping cluster0-shard-00-01.whzdc.mongodb.net"}, {"role": "user", "content": "Text:I\u2019ve been trying to connect using company wifi, excuse me for not knowing much about networking but I guess it\u2019s because there\u2019s some system in place that\u2019d prevent me from connecting to addresses like these.\nIt seems to work completely fine when I\u2019m at home for some reason.When I ping the cluster:I installed the mongo shell and attempted to connect to the cluster, still got a timeout after ~30s\nCode:absl-py 0.13.0\naiohttp 3.6.3\nanime-downloader 5.0.7\nanimethemes-dl 2.2.2.3\nappconfigpy 1.0.2\nappdirs 1.4.4\nart 5.1\nastunparse 1.6.3\nasync-timeout 3.0.1\nasyncio-dgram 2.0.0\natomicwrites 1.4.0\nattrs 20.3.0\nAutomat 20.2.0\nautopep8 1.5.4\nbackcall 0.2.0\nbcrypt 3.2.0\nbeartype 0.5.1\nbeautifulsoup4 4.9.3\nbinary 1.0.0\nblack 21.6b0\nbleach 3.2.1\nblinker 1.4\nboto3 1.16.56\nbotocore 1.19.56\nBrotli 1.0.9\nbrowser-cookie3 0.12.1\nbrowsermob-proxy 0.8.0\nbs4 0.0.1\nbson 0.5.10\nCacheControl 0.12.6\ncachetools 4.2.1\ncachy 0.3.0\ncertifi 2020.12.5\ncffi 1.14.5\ncfscrape 2.1.1\nchardet 3.0.4\ncleo 0.8.1\nclick 7.1.2\nclikit 0.6.2\ncloudscraper 1.2.58\ncolorama 0.4.4\ncoloredlogs 15.0\ncommonmark 0.9.1\nconstantly 15.1.0\ncrashtest 0.3.1\ncryptography 3.3.1\ncssselect 1.1.0\ncv 1.0.0\ncycler 0.10.0\nCython 0.29.21\nDataProperty 0.50.0\ndebtcollector 2.2.0\ndebugpy 1.3.0\ndecorator 4.4.2\ndecouple 0.0.7\ndeprecation 2.1.0\ndeskew 0.10.32\ndiscord 1.0.1\ndiscord-pretty-help 1.3.2\ndiscord.py 1.7.2\ndiscord.py-stubs 1.7.1\nDiscordUtils 1.2.6\ndiscum 1.0.1\ndistlib 0.3.2\ndnspython 2.1.0\ndoc-search 1.0.7\ndocutils 0.16\nEditorConfig 0.12.3\nenvinfopy 0.0.3\nexcelrd 2.0.3\neyeD3 0.9.5\nfake-useragent 0.1.11\nfasttext 0.9.2\nfeedparser 6.0.8\nfilelock 3.0.12\nfiletype 1.0.7\nfirebase-admin 4.5.2\nFlask 1.1.2\nFlask-Cache 0.13.1\nFlask-Caching 1.10.0\nFlask-Cors 3.0.10\nflask-swagger 0.2.14\nflatbuffers 1.12\nfuture 0.18.2\nfuzzywuzzy 0.18.0\ngallery-dl 1.16.5\ngast 0.4.0\ngenshinstats 1.4.4.1\ngenshinstats-api 1.1\ngmail 0.6.3\ngoogle 3.0.0\ngoogle-api-core 1.26.1\ngoogle-api-python-client 2.3.0\ngoogle-auth 1.27.1\ngoogle-auth-httplib2 0.1.0\ngoogle-auth-oauthlib 0.4.4\ngoogle-cloud-bigquery 2.13.0\ngoogle-cloud-core 1.6.0\ngoogle-cloud-firestore 2.0.2\ngoogle-cloud-storage 1.36.1\ngoogle-crc32c 1.1.2\ngoogle-pasta 0.2.0\ngoogle-resumable-media 1.2.0\ngoogleapis-common-protos 1.53.0\ngooglemaps 4.4.5\ngoogletrans 3.0.0\ngreenlet 1.0.0\ngrpcio 1.34.1\ngunicorn 20.0.4\nh11 0.9.0\nh2 3.2.0\nh5py 3.1.0\nhpack 3.0.0\nhstspreload 2020.12.22\nhtml2markdown 0.1.7\nhtml5lib 1.1\nhttpcore 0.9.1\nhttplib2 0.19.0\nhttpx 0.13.3\nhumanfriendly 9.1\nhumanize 3.7.0\nhyperframe 5.2.0\nhyperlink 21.0.0\nidna 2.8\nimageio 2.9.0\nincremental 21.3.0\niniconfig 1.1.1\nipykernel 6.0.2\nipython 7.25.0\nipython-genutils 0.2.0\niso8601 0.1.13\nitemadapter 0.2.0\nitemloaders 1.0.4\nitsdangerous 1.1.0\njedi 0.18.0\njeepney 0.6.0\nJinja2 2.11.3\njmespath 0.10.0\njoblib 1.0.1\nJs2Py 0.71\njsbeautifier 1.13.5\njsonpointer 2.1\njsonschema 3.2.0\njupyter-client 6.1.12\njupyter-core 4.7.0\nkaitaistruct 0.9\nKeras 2.4.3\nkeras-nightly 2.5.0.dev2021032900\nKeras-Preprocessing 1.1.2\nkeyboard 0.13.5\nkeyring 21.5.0\nkiwisolver 1.3.1\nlockfile 0.12.2\nloguru 0.5.3\nlxml 4.6.3\nlz4 3.1.3\nMako 1.1.4\nmando 0.6.4\nMarkdown 3.3.3\nMarkupSafe 1.1.1\nmatplotlib 3.4.2\nmatplotlib-inline 0.1.2\nmbstrdecoder 1.0.1\nmcstatus 6.1.0\nmechanize 0.4.5\nmock 4.0.3\nmotor 2.4.0\nMouseInfo 0.1.3\nmsgfy 0.1.0\nmsgpack 1.0.2\nmultidict 4.7.6\nmutagen 1.45.1\nmypy 0.800\nmypy-extensions 0.4.3\nmysql 0.0.2\nmysql-connector-python 8.0.23\nmysqlclient 2.0.3\nnbformat 5.0.8\nnetaddr 0.8.0\nnetifaces 0.11.0\nnetworkx 2.5.1\nnltk 3.6.2\nnumpy 1.21.1\noauth2client 4.1.3\noauthlib 3.1.0\nopencv-python 4.5.1.48\nopt-einsum 3.3.0\norjson 3.5.2\nos-service-types 1.7.0\noslo.i18n 5.0.1\npackaging 20.9\npandas 1.2.0\nparse 1.19.0\nparsel 1.6.0\nparso 0.8.2\npastel 0.2.1\npath 15.0.1\npath.py 12.5.0\npathspec 0.8.1\npathvalidate 2.3.1\npbkdf2 1.3\npbr 5.6.0\npdoc3 0.9.2\npeewee 3.13.3\npexpect 4.8.0\nphonenumbers 8.12.21\npickleshare 0.7.5\nPillow 8.1.0\npip 21.1.3\npip-check-reqs 2.2.0\npkginfo 1.6.1\nplotly 5.1.0\npluggy 0.13.1\npoetry 1.1.6\npoetry-core 1.0.3\npraw 7.2.0\nprawcore 2.0.0\npriority 1.3.0\nprompt-toolkit 3.0.18\nProtego 0.1.16\nproto-plus 1.14.2\nprotobuf 3.15.5\npsutil 5.8.0\nptyprocess 0.7.0\npy 1.10.0\npyaes 1.6.1\npyasn1 0.4.8\npyasn1-modules 0.2.8\nPyAutoGUI 0.9.52\npybind11 2.7.0\nPyBluez 0.23\npycana 0.1\npycodestyle 2.6.0\npycparser 2.20\npycryptodome 3.10.1\npycryptodomex 3.9.9\npydantic 1.8.2\nPyDispatcher 2.0.5\npydivert 2.1.0\nPyDrive 1.3.1\npyee 8.1.0\npyfiglet 0.8.post1\npygame 2.0.1\nPyGetWindow 0.0.9\nPygments 2.8.1\npyjsparser 2.7.1\npylev 1.4.0\npymongo 3.12.0\nPyMsgBox 1.0.9\nPyMySQL 1.0.2\nPyNaCl 1.4.0\npynput 1.7.3\npyOpenSSL 20.0.1\npyparsing 2.4.7\npyperclip 1.8.1\npypinfo 19.0.0\npyppeteer 0.2.5\nPyQt5 5.15.2\nPyQt5-sip 12.8.1\npyquery 1.4.3\npyreadline 2.1\npyreadline3 3.3\nPyRect 0.1.4\npyrsistent 0.17.3\nPyScreeze 0.1.26\nPySimpleGUI 4.39.1\npySmartDL 1.3.4\nPySocks 1.7.1\npytablereader 0.30.1\npyte 0.8.0\npytesseract 0.3.8\npytest 6.2.3\npython-brainfuck 0.9.1\npython-dateutil 2.8.1\npython-gmaps 0.3.1\npython-Levenshtein 0.12.1\npytube 10.8.4\nPyTweening 1.0.3\npytz 2020.5\nPyWavelets 1.1.1\npywin32 300\npywin32-ctypes 0.2.0\nPyYAML 5.1\npyzmq 22.1.0\nqueuelib 1.5.0\nradon 5.0.1\nrandom-user-agent 1.0.1\nrapidfuzz 1.0.0\nreadme-renderer 28.0\nregex 2020.11.13\nrequests 2.25.1\nrequests-cache 0.5.2\nrequests-html 0.10.0\nrequests-oauthlib 1.3.0\nrequests-toolbelt 0.9.1\nrequestsexceptions 1.4.0\nretryrequests 0.0.3\nrfc3986 1.4.0\nrich 9.11.0\nrsa 4.7.2\ns3transfer 0.3.4\nscikit-image 0.18.2\nscikit-learn 0.24.2\nscipy 1.5.4\nScrapy 2.5.0\nseaborn 0.11.1\nSecretStorage 3.3.1\nselenium 3.141.0\nselenium-wire 4.0.4\nsentry-sdk 0.19.4\nservice-identity 18.1.0\nsetuptools 56.0.0\nsgmllib3k 1.0.0\nshellingham 1.4.0\nSimpleSQLite 1.1.4\nsix 1.15.0\nsniffio 1.2.0\nsoupsieve 2.1\nspotdl 3.6.1\nspotipy 2.18.0\nSQLAlchemy 1.4.12\nsqlitebiter 0.34.1\nsqliteschema 1.0.5\nstevedore 3.3.0\nstockfish 3.13.0\ntabledata 1.1.3\ntabulate 0.8.7\ntcolorpy 0.0.8\ntenacity 8.0.1\ntensorboard 2.5.0\ntensorboard-data-server 0.6.1\ntensorboard-plugin-wit 1.8.0\ntensorflow 2.5.0\ntensorflow-estimator 2.5.0\ntermcolor 1.1.0\nthefuck 3.30\nthreadpoolctl 2.2.0\ntifffile 2021.7.2\ntinydb 4.4.0\ntinyrecord 0.2.0\ntoml 0.10.2\ntomlkit 0.7.2\ntornado 6.1\ntox 3.23.1\ntqdm 4.56.0\ntraitlets 5.0.5\ntwine 3.3.0\nTwisted 21.2.0\ntwisted-iocpsupport 1.0.1\ntyped-ast 1.4.2\ntypeguard 2.12.1\ntypepy 1.1.2\ntyping-extensions 3.7.4.3\ntzlocal 2.1\nua-parser 0.10.0\nujson 4.0.2\nUnidecode 1.2.0\nupdate-checker 0.18.0\nuritemplate 3.0.1\nurllib3 1.26.4\nvirtualenv 20.4.7\nw3lib 1.22.0\nwcwidth 0.2.5\nwebencodings 0.5.1\nwebsocket-client 0.57.0\nwebsockets 8.1\nWerkzeug 1.0.1\nwheel 0.36.2\nwin-unicode-console 0.5\nwin32-setctime 1.0.3\nwrapt 1.12.1\nwsproto 1.0.0\nXlsxWriter 1.4.0\nyarl 1.5.1\nyoutube-dl 2021.5.16\nytmusicapi 0.14.3\nzipp 3.4.1\nzope.interface 5.3.0\n> ping cluster0-shard-00-01.whzdc.mongodb.net\n\nPinging ec2-18-196-119-49.eu-central-1.compute.amazonaws.com [18.196.119.49] with 32 bytes of data:\nReply from 18.196.119.49: bytes=32 time=19ms TTL=39\nReply from 18.196.119.49: bytes=32 time=19ms TTL=39\nReply from 18.196.119.49: bytes=32 time=19ms TTL=39\nReply from 18.196.119.49: bytes=32 time=19ms TTL=39\n\nPing statistics for 18.196.119.49:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 19ms, Maximum = 19ms, Average = 19ms\n> mongosh cluster0-shard-00-01.whzdc.mongodb.net\n\nCurrent Mongosh Log ID: 60f7ca8b2aae42386b38edb3\nConnecting to: mongodb://cluster0-shard-00-01.whzdc.mongodb.net:27017/test?directConnection=true\nMongoServerSelectionError: connect ETIMEDOUT 18.196.119.49:27017\n"}, {"role": "assistant", "content": "Text:Hi, Make sure you entered the user password, not the MongoDB account password. I encountered similar issue.\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m having the same issue. Is there no solution for this? I tried to do what @shane told and got the same results as @sadru.\nCode:"}, {"role": "assistant", "content": "Text:This thread is 2 months old.Please start a new thread and post a screenshot of what you are trying that shows the issue you are having.If you could not resolve your issue with what was posted in this thread, then your issue is slightly different and should be on its own thread.\nCode:"}, {"role": "assistant", "content": "Text:I am going through the same problem recently. Did you get any solution to this issue?\nCode:"}, {"role": "assistant", "content": "Text:As already mentionedThis thread is 2 months old.Now 3 months, and more since the original message.As already mentionedIf you could not resolve your issue with what was posted in this thread, then your issue is slightly different and should be on its own thread.As already mentionedPlease start a new thread and post a screenshot of what you are trying that shows the issue you are having.\nCode:"}, {"role": "assistant", "content": "Text:Hello, buddy.\nI had this problem before, so i have tried everything to solve it and i did.\nSo, most probably you added your own ip adress when you were creating a db, but you need to allow all the ip adresses that will connect to your db.\nYou may change it in your page in network access.\nThank you for attention! \nI hope it will be useful for you.\nCode:"}, {"role": "assistant", "content": "Text:Couldn\u2019t connect with enabled VPN (ProtonVPN). Works without it.\nCode:"}, {"role": "assistant", "content": "Text:@sadru Go to Mongo db atlas dashboard\nSelect your current project\nclick on Network Access (left side menu)\nIn the \u201cIP Access List\u201d tab\nMake sure you don\u2019t have an old dynamic IP of your machine set there\nOr you can add 0.0.0.0/0 (includes your current IP address) to access from anywhere\nCode:"}, {"role": "assistant", "content": "Text:This worked for me, thanks you so much\nCode:"}, {"role": "assistant", "content": "Text:You\u2019re the most generous Lord in all the Land, thank you sir \nCode:"}, {"role": "assistant", "content": "Text:Thx bro you are a truly god\nCode:"}, {"role": "assistant", "content": "Text:Another solution-\nI created a SCRAM user in the database access tab.\nThen, I added &authSource=the_database&authMechanism=SCRAM-SHA-1 to the connection string. Like this:\nCode:connect_string = 'mongodb+srv://{}:{}@{}/?retryWrites=true&authSource=the_database&authMechanism=SCRAM-SHA-1'.format(username, password, hostname)\npy_client = MongoClient(connect_string)\n"}, {"role": "assistant", "content": "Text:I asked a team member in chat and they gave a working answer!This is what they said:\nIf you are receiving an SSL certificate error when connecting to your Atlas cluster with PyMongo, such as:This indicates that Python does not have access to the system\u2019s root certificates.This often occurs because OpenSSL does not have access to the system\u2019s root certificates or the certificates are out of date. Linux users should ensure that they have the latest root certificate updates installed from their Linux vendor.A sample command script is included in \u201c/Applications/Python \u201d to install a curated bundle of default root certificates from the third-party certifi package. Open a terminal window and run the following command, with your Python version.Alternatively, you can head to the Applications folder in Finder and double click \u201cInstall Certificates.command\u201d to run the script:\nCode:unable to get local issuer certificate [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed open \"/Applications/Python /Install certificates.command\"\n"}, {"role": "assistant", "content": "Text:I logged in to thanks you very much \nCode:"}, {"role": "assistant", "content": "Text:Not sure how special it is but for me it works by replacing the url with mongodb+srv://:@cluster0.gr4blbt.mongodb.net/?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true&w=majorityBasically adding ssl=true&ssl_cert_reqs=CERT_NONE and remove the \u201c?\u201d in the end\nCode:"}, {"role": "assistant", "content": "Text:ssl_cert_reqs=CERT_NONE is insecure and not recommended. See ServerSelectionTimeoutError [SSL: CERTIFICATE_VERIFY_FAILED] Trying to understand the origin of the problem for how to fix TLS errors securely.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: GraphQL query string filters like \"StartsWith\" or \"Contains\" and tags: ['graphql']"}, {"role": "user", "content": "Text:I have generated GraphQL queries on realm app based on the schema. Generated GraphQL query has multiple filter options like _exists, _in, _gt, _lt, _nin, _gte etc.I\u2019m looking to fetch all the records where name starts with \u201cxyz\u201d or string contains any given word. Can anyone suggest how to apply such filters?\nCode:"}, {"role": "assistant", "content": "Text:Hi Vivek \u2013 For this case we would recommend creating a custom resolver that leverages MongoDB\u2019s Text Search.\nCode:"}, {"role": "user", "content": "Text:thanks for the response Drew,I would imagine taking the custom resolver route for any specialized functionality where I have the freedom to implement the behaviour I want. However regex pattern matching on string fields should be part of auto-generated filters.Do you think it could be implemented as generic feature at some point in future? or, are there any risks etc in adding it to default auto-generated filters like lack of indexes?\nCode:"}, {"role": "assistant", "content": "Text:Hi Vivek \u2013 We\u2019re definitely considering adding a Regex pattern to our defaults but don\u2019t have a timeline for when this would be added. This is slightly complicated by the fact that $search is becoming the recommendation for use cases like this but requires additional set-up on the cluster.\nCode:"}, {"role": "assistant", "content": "Text:I am using the graphQL custom resolvers, and while they will do what you want, you are now operating outside the autogenerated types. For instance, you cannot combine things like in, greater than, less than with the custom resolvers because you have to rewrite all that.A better solution would be to add custom Query Inputs. I get that $search is recommended from the database perspective, but I already have to look at the pros and cons of searching. I just want to extend the GraphQL schema a bit more than just a custom resolver.\nCode:"}, {"role": "assistant", "content": "Text:+1. It\u2019s frustrating to have to choose between all the generated options that map to find automatically (lt, gt, etc) and a custom resolver to implement missing features like pagination or search.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Problems installing MongoDB on Ubuntu 20.04 and tags: ['installation']"}, {"role": "user", "content": "Text:Following the documentation for Mongo 4.4 on Ubuntu, I get the key, add the repository, then get the following error when running atp-get update:If I try to curl to the page I get the following:Am I looking at a key issue or is something not right with the repo?\nCode:Err:6 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 Release\nCould not handshake: The TLS connection was non-properly terminated. [IP: 185.46.212.98 9480]\nReading package lists... Done\nE: The repository 'https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 Release' does not have a Release file.\nN: Updating from such a repository can't be done securely, and is therefore disabled by default.\nN: See apt-secure(8) manpage for repository creation and user configuration details.\n\n404 Not Found\n\n

404 Not Found

\n
    \n
  • Code: NoSuchKey
  • \n
  • Message: The specified key does not exist.
  • \n
  • Key: apt/ubuntufocal/mongodb-org/4.4multiverse
  • \n
  • RequestId: C5JWFBGFTN5X4B10
  • \n
  • HostId: RHZGG+Mt6t/Gmo25ZCTy1L5+8NaZiz+NqCuDxYYd8iTyiKjMuUvUKU3Zm+gKbbJd5H5aMzal+fQ=
  • \n
\n
\n\n\n"}, {"role": "assistant", "content": "Text:https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 ReleasePlease have a look on below link and follow steps for ubuntu 20MongoDB is an open-source document database used commonly in modern web applications. It is classified as a NoSQL database because it does not rely on a tra\u2026\nCode:https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 Release"}, {"role": "user", "content": "Text:I have been following every guide I can find.\nCode:"}, {"role": "assistant", "content": "Text:Hi @jon_rawlins,I tried above mongodb link on which worked for me.image1230\u00d794 18.1 KBimage1589\u00d7154 39.1 KBimage1556\u00d7743 194 KB\nCode:"}, {"role": "assistant", "content": "Text:I am also experiencing this issue trying to install MongoDB 4.4 on Ubuntu 20.04LTS \u2026 This mentions no release file for focal when I try apt update (after adding the PGP key of course). @jon_rawlins did you find a workaround for this?\nCode:"}, {"role": "assistant", "content": "Text:the fix for this to change this line\u2026 basically remove 4.4 on the saved file \u2026echo \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.listto this\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org.list\nCode:echo \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.listecho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org.list"}, {"role": "assistant", "content": "Text:Hopefully, this can be helpful for installing MongoDB version 3.4.17\nTry this:\nCode:echo \"deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list\n\nsudo apt update\n\n\napt-cache policy libssl1.0-dev\n\nsudo apt-get install libssl1.0-dev\n\n\nsudo apt-get install -y mongodb-org=3.4.17 mongodb-org-server=3.4.17 mongodb-org-shell=3.4.17 mongodb-org-mongos=3.4.17 mongodb-org-tools=3.4.17"}, {"role": "assistant", "content": "Text:Update, please also run this step of adding repository keys as the first step before running any of the other steps mentioned above:Apologies for the inconvenience!\nCode:sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6\n"}, {"role": "assistant", "content": "Text:tried everything but doesnot work\n\nimage953\u00d7526 197 KB\n\nCode:"}, {"role": "assistant", "content": "Text:@Suman_Osti please update if you find any solution\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongoose connect is not a function... What is wrong? and tags: ['node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:I have tried to connect mongodb to REACT in a million different ways, using uri, putting the code straight on the ./app, doing the connection in another file and requiring it in the ./app page\u2026 nothing has worked.I believe I have the username and password just fine, along with the database name\u2026Why am I keep getting these errors and not able to connect?snip2891\u00d7497 29.8 KB\nCode:"}, {"role": "user", "content": "Text:I have tried tons of different codes\u2026 this is just one of them\u2026\nCode:const mongoose = require(\"mongoose\");\n\nconst connection =\n\n \"mongodb+srv://:@cluster0.gcyyo.mongodb.net/?retryWrites=true&w=majority\";\n\nmongoose\n\n .connect(connection, {\n\n useNewUrlParser: true,\n\n useUnifiedTopology: true,\n\n useFindAndModify: false,\n\n })\n\n .then(() => console.log(\"Database Connected Successfully\"))\n\n .catch((err) => console.log(err));\n"}, {"role": "assistant", "content": "Text:Did you get through? Im trying with Svelte 3.49 and Vite 3.1.0 using ES6 and I get the same error. Tried lots of \u201csolutions\u201d. None work. So frustrating how krappy web software is. I developed software for years on pc and most of the time it krapped out was human error. Web software is bug infested!\nCode:"}, {"role": "assistant", "content": "Text:Has any solution been found for this issue?\nI am having the same problem now.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Error : couldn't connect to server 127.0.0.1:27017, connection attempt failed : Socket Exception and tags: []"}, {"role": "user", "content": "Text:Hello Dear Community,I am facing this error :MongoDB shell version v4.4.14\nconnecting to : mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb\nError: couldn\u2019t connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :\nconnect@src/mongo/shell/mongo.js:374:17\n@(connect):2:6\nexception: connect failed\nexiting with code 1I am on Ubuntu 16.04 and I am basically trying to encrypt data from client to server using TLS/SSL. So, I created a CA file and I am trying to connect to mongodb using that certificate with this command :mongo --tls --tlsCAFile rootCA.pem --host 127.0.0.1However even the command \u201cmongo\u201d gives me this error. I am new to Linux so I do not know how to verify that mongodb is on the right IP and port could you please show step by step ?\nCode:"}, {"role": "assistant", "content": "Text:Is your mongod up and running on port 27017?\nps -ef|grep mongo or check from service status depending on your install method\nIs it running as service or manually started from command line?\nCode:"}, {"role": "user", "content": "Text:Hello, thank you for your response : when I run \u201cps -ef|grep mongo\u201d I get this output :And I am sorry but I don\u2019t know weather mongod is running as a service but I installed it manually.\nCode:"}, {"role": "assistant", "content": "Text:Your mongod is up & running\nPlease show contents of your config file\nCode:"}, {"role": "user", "content": "Text:This is the content of my mongod.conf file :Thank you for your time\nCode:# mongod.conf\n\n# for documentation of all options, see:\n# http://docs.mongodb.org/manual/reference/configuration-options/\n\n# Where and how to store data.\nstorage:\n dbPath: /var/lib/mongodb\n journal:\n enabled: true\n# engine:\n# mmapv1:\n# wiredTiger:\n\n# where to write logging data.\nsystemLog:\n destination: file\n logAppend: true\n path: /var/log/mongodb/mongod.log\n\n# network interfaces\nnet:\n port: 27017\n bindIp: 127.0.0.1\n tls :\n mode : requireTLS\n certificateKeyFile : /home/youssef/mongodb.pem\n CAFile : /home/youssef/rootCA.pem\n\n# how the process runs\nprocessManagement:\n timeZoneInfo: /usr/share/zoneinfo\n\n#security:\n\n#operationProfiling:\n\n#replication:\n\n#sharding:\n\n## Enterprise-Only Options:\n\n#auditLog:\n\n#snmp:\n"}, {"role": "assistant", "content": "Text:port: 1687It is running on port 1687\nSo connect by\nmongo --port 1687\nCode:port: 1687"}, {"role": "user", "content": "Text:No sorry I just changed the port to try out some tests. the actual port is 27017. And even when I specify port 1687 it gives me the same error\nCode:"}, {"role": "user", "content": "Text:In this post : Error: couldn't connect to server 127.0.0.1:27017 - #4 by Stephen_Fuller it says I need to create some directories because me too when I run the command : \" netstat -an | grep 27017` \" I don\u2019t get any output. But I don\u2019t know what I have to do since it is not stated clearly in the other post\nCode:"}, {"role": "assistant", "content": "Text:Check your mongod.log for more errors\nCd to your dbpath dir if it exists no need to create first\nThe command i gave is to connect assuming your mongod is running with no acces control\nSince you say your mongod runs on port 27017 please check step by step first whether you can connect without security parms enabled\nShutdown your mongod edit config file and comment the security params.Start mongod and try to connect issuing just mongo\nIf you can connect then add back tls and other params and investigate why it is not working\nCode:"}, {"role": "user", "content": "Text:This is the actual error I am getting from the logs :\u201cmsg\u201d:\u201cError receiving request from client. Ending connection from remote\u201d,\u201cattr\u201d:{\u201cerror\u201d:{\u201ccode\u201d:141,\u201ccodeName\u201d:\u201cSSLHandshakeFailed\u201d,\u201cerrmsg\u201d:\u201cSSL handshake received but server is started without SSL support\u201d},\u201cremote\u201d:\u201c127.0.0.1:34766\u201d,\u201cconnectionId\u201d:4}}But how do I start the server with ssl support ?\nCode:"}, {"role": "assistant", "content": "Text:See https://www.mongodb.com/docs/manual/reference/configuration-options/#net-options.If you are planning to manage your own server, I strongly recommend you take MongoDB Courses and Trainings | MongoDB University. Question like this one are covered.\nCode:"}, {"role": "user", "content": "Text:I already took that course and although it mentions TLS encryption it doesn\u2019t describe how to implement it \nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Slow connection to the server using NodeJS driver and tags: ['node-js', 'connecting', 'performance']"}, {"role": "user", "content": "Text:Hello mongo gurus,I recently signed up for the mongo atlas to eliminate some of the operational challenges of my own hosted/self managed community edition.My app seems operational after changing the driver and connection string in uri (mongo+srv) format.However, it takes close to 25 seconds to establish the initial connection. **That's really slow.**Any help to improve the performance of the initial connection would be greatly appreciated.Here my stack.Node.js - v10.18.1driver - \u201cmongodb\u201d: \"^3.6connection codethank you,\nJag\nCode:**That's really slow.**const MongoClient = require('mongodb').MongoClient;\nurl = `mongodb+srv://${process.env.mongo_user}:${process.env.mongo_password}@${process.env.mongo_host}/${process.env.mongo_db}?retryWrites=true&w=majority`\n\n MongoClient.connect(url,\n {\n useUnifiedTopology: true,\n useNewUrlParser: true\n }).then((client) => {\n\n console.log(\"mongo db conection success\");\n \n }).catch(err => {\n console.log(\"connection failure.... \", url);\n console.log(\"connection errored \", err);\n })\n"}, {"role": "assistant", "content": "Text:Hi Jag,I am having the same issue. However for me this started happening suddenly with no clear explanation. I am using nodemon for hot reloading. For months I have been working on an application that would connect to MongoDB using mongoose and every time there was a reload it would reconnect to Mongo within milliseconds. Now it has consistently been taking 20+ seconds to connect on every reload.I cannot figure out what caused this to start happening and how to fix it. If anyone has any advice, it would be greatly appreciated.\nCode:"}, {"role": "assistant", "content": "Text:Same here, connection to database is very slow and await doc.save() is not finishing\nCode:"}, {"role": "assistant", "content": "Text:Can you test the connection with Compass and the shell to see if there are similar slow downs to the Node.js driver? This will eliminate the driver as the point of failure?\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m having the same issue. I have 2 pc, on the first one the connection take less than 1s, one the 2nd one, the connection take 20s \u2026 they are connected to the same network and using the same version of node. 2 days ago I had no issue.\nI have try to connect with mongoDB compass on windows 10 after I enter the url, the app is loading forever \u2026 (I\u2019ve try to connect several times)\nCode:"}, {"role": "assistant", "content": "Text:Hi all,Hopefully this will help:\nCode:"}, {"role": "assistant", "content": "Text:Hopefully this will help:Thanks, indeed using the url given when using the mongo shell seems to work.\nCode:"}, {"role": "assistant", "content": "Text:Try rebooting your router. This is what fixed the issue for me.When using SRV the driver initiates a lookup that resolves a single hostname to the actual names of the hosts, this is the step that was causing the issue for me. I still do not know why my router was interfering with the SRV lookup specifically - my internet connection was otherwise perfect. I would love if someone could elaborate on why rebooting my router resolved this issue?\nCode:"}, {"role": "assistant", "content": "Text:As ridiculous as it sounds, rebooting my router did fix the issue for me. More specifically, DNS was messed up. After restarting my router and my Pihole docker container, DNS issues resolved (I hadn\u2019t noticed having any anyway), and it no longer takes me 20 seconds to connect to a MongoDB Atlas instance.\nCode:"}, {"role": "assistant", "content": "Text:I tried different things:What worked for me, was that I changed my network settings use Google Public DNS, instead of my ISP\u2019s DNS servers (I have a cheap ASUS router). After that I am now connection to my MongoDB within 2-4 seconds, which is about 10 times faster than before.Here is how to do it: Get Started \u00a0|\u00a0 Public DNS \u00a0|\u00a0 Google Developers\nCode:"}, {"role": "assistant", "content": "Text:You don\u2019t need to reboot your router none of that, you just need a VPN im using Urban VPN Desktop its free and its an easy fix\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongosh command not working in Bash shell and tags: ['sharding', 'mongodb-shell']"}, {"role": "user", "content": "Text:First of all, a bit of background: I\u2019m currently working through a Udemy course. The instructor demos installing MongoDB 4.0, then running mongod in hyper (as the instructor is using a Mac), then opening a new shell and running mongo.I\u2019m trying to achieve the same outcome with MongoDB 6.0.3. I know that now MongoDB uses a separate shell, mongosh. I downloaded the shell and put it in the bin with the other MongoDB downloads. I also set the path environmental variables. When I run the mongod command in the Bash terminal, it seems to be working, but when I open a new Bash shell and run mongosh, it\u2019s giving me errors. I tried the commands for mongo or mongos, and still not working.I wanted to share screencaps here, as I think that\u2019d be more helpful, but it looks like I\u2019m going to need to clean off some diskspace to run Photoshop, so for now I hope these descriptions will help. Here is what I\u2019m seeing in the Bash shell when I run each command:\u201c$ mongosh\nbash: mongosh: command not found\u201d\u201c$ mongo\nBadValue: error: no args for --configdb\ntry \u2018C:\\Program Files\\MongoDB\\Server\\6.0\\bin\\mongos.exe --help\u2019 for more information\u201dI double-checked, and my mongosh file is definitely in \u201cC:\\Program Files\\MongoDB\\Server\\6.0\\bin\u201d, which is the path I set in the environmental variables section.I followed what this guy did in the video: Mongo command is not working/found in MongoDB 6.0+ || MongoDB error fix - YouTube \u2013 with the one difference being that I put my mongosh file with the other MongoDB files in the bin folder\u2026 though I don\u2019t see that this would make a difference. But when I run the \u201cmongosh\u201d command in Bash, I get the error above. I\u2019m confused, as it seems to work fine for him in the tutorial video, so I came here, as I\u2019m quite frustrated with trying to troubleshoot at this point. I\u2019ve been troubleshooting MongoDB installations issues for a while now, between this and other differences in the updated version, and browsing here and Stack Overflow, but still confused as to why it\u2019s not working.Any help would be appreciated! Thanks!Edit: Oh my gosh. I just decided to try the command CLI rather than the Bash shell, and\u2026 it works on the command prompt, but not the Bash shell. I suppose I can use the command prompt, but now I\u2019m confused why it\u2019s not working in the Bash shell. I feel a little silly realizing this after typing all that, but I do prefer to work in the Bash shell if possible.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Amber_Adamson! I don\u2019t have a complete answer for you, but here\u2019s the troubleshooting that I\u2019d do if I were in your situation:Finally, this is not related to troubleshooting but points to something being wrong in general:mongo and mongos are different executables, so if mongo self-identifies as mongos and reports an error that only mongos should ever really report, there\u2019s most likely something else wrong with the MongoDB installation here as well.\nCode:echo $PATHwhich mongoshtype mongoshwhich mongowhich mongodhash -rmongoshmongosh$ mongo\nBadValue: error: no args for --configdb\ntry \u2018C:\\Program Files\\MongoDB\\Server\\6.0\\bin\\mongos.exe --help\u2019 for more information\nmongomongosmongomongosmongos"}, {"role": "assistant", "content": "Text:How are you running bash on Windows? Is this in WSL?You would need to install mongosh inside WSL if you are.\nCode:"}, {"role": "assistant", "content": "Text:I found this post looking for a way to make the mongoDB shell work properly in bash, which I installed on Windows 10 as part of a git installation. Everything works, but whilst mongosh works perfectly using the Windows CLI, all the nice features of mongosh are lost in bash. Indeed, I found it quite error prone in bash, so I just keep on using it with the CLI.\nCode:"}, {"role": "assistant", "content": "Text:What I did on windows was, I installed mongosh and created an alias and placed it\u2019s location in .bash_profile using vim, just below mongod and mongos\nCode:"}, {"role": "assistant", "content": "Text:Thanks, Krimier_Dan_Sanz. Your response prompted me to put some more effort to the problem, and I now found the solution that works best for me. I can simply run the mongosh shell in a Visual Studio Code terminal, and it works perfectly.\nCode:"}, {"role": "assistant", "content": "Text:Just putting the solution here for anyone looking:To install MongoDB (version 5.0) on WSL (Ubuntu 20.04):Source\nCode:cd ~sudo apt updatewget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -echo \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.listsudo apt-get updatesudo apt-get install -y mongodb-orgmongod --versionmkdir -p ~/data/dbsudo mongod --dbpath ~/data/dbps -e | grep 'mongod'"}, {"role": "assistant", "content": "Text:I\u2019ve been asked to post my solution for running the mongosh shell in VS Code. I\u2019ll gladly do so, with the understanding that this is not specifically a solution to the OP\u2019s question about \u201cmongosh command not working in Bash shell\u201d. I understand that the OP\u2019s question has been resolved. Running mongosh in a Bash terminal was suboptimal to me, and running it in a VS Code terminal became my preferred solution; not least, because I\u2019m also using this for learning web development. Assuming a problem-free installation of VS Code on Windows 10, my solution was really quite simple. Just add the mongosh.exe path to the sytem\u2019s Path environment variable; in my case C:\\Program Files\\MongoDB\\Shell\\bin. Open a terminal in VS Code, which in my case by default runs Powershell. At the PS prompt, enter: mongosh. The terminal now runs the mongosh shell, and displays the usual mongosh prompt. Two advantages:\nCode:"}, {"role": "user", "content": "Text:I\u2019m the OP, coming back to this a few months later. First of all, I have to say, I\u2019m really embarrassed to admit I used some imprecise terminology in my original post\u2026 which undoubtedly led to confusion. I was working with the Gitbash terminal on my Windows, which I was referring to as \u201cBash\u201d as short for GITBASH\u2026 which was undoubtedly confusing, since anyone would assume I was using a Linux Bash shell, maybe via an Ubuntu VM or something. I have since worked with a Linux Bash shell, so I would be a lot more precise with my terminology and differentiation now. Though I know Git Bash reproduces Bash features, I still think I should\u2019ve been a bit more precise about what I was working with, as I basically led everyone to assume I was working with a Linux shell.I\u2019m not sure I ever figured out why mongosh wasn\u2019t working on Gitbash. I just started using the command prompt instead, as it worked.\nCode:"}, {"role": "assistant", "content": "Text:Hello! I think I solved this problem. After downloading \u201cmongoDB shell\u201d, make sure that it is saved in \u201cProgram Files\u201d on your C drive. You should be able to access this from \u201cMy PC\u201d then you have to go to that file \u201cmongosh\u201d and go to bin, then make a copy of the file that has a little green leaf on it. Take the copy and go back into \u201cProgram Files\u201d where you originally downloaded your monggDB-different from mongosh. Open that folder until you get to bin. Add a coy of mongosh to the bin of your mongoDB. Also, Make sure your mongoDB bin is in \u201csystem enviorenmental variables\u201d I hope this helps someone!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Whether Realm sync can be work with IonicFramework? and tags: ['atlas-device-sync']"}, {"role": "user", "content": "Text:Whether Realm sync can be work with IonicFramework?\nCode:"}, {"role": "assistant", "content": "Text:Hi and welcome to the Community.Currently we only support React Native (both iOS & Android) and Node.js (on MacOS and Linux) but we are considering adding support for Cordova/PhoneGap/Ionic as well, but we have no exact timelines as yet. Stay tuned here, and via @realm on Twitter too for any updates.\nCode:"}, {"role": "assistant", "content": "Text:Hi Shane,\nThe ionic community is huge and it would be awesome to have Ionic integrate with Realm.\nWe look forward to it.\nAny news?\nCode:"}, {"role": "assistant", "content": "Text:Hi Alan - good timing. We\u2019ve just completed a proof of concept with Ionic and we are looking forward to sharing that with the community very soon - stay tuned! And thanks for following up on this thread - I should have kept it updated!\nCode:"}, {"role": "assistant", "content": "Text:Hi Shane,I look forward to it.Thank you for yoir reply.\nCode:"}, {"role": "assistant", "content": "Text:No problem - as soon as we can share details - I\u2019ll update this post.\nCode:"}, {"role": "assistant", "content": "Text:Hi ShaneAm also very interested in this development.\nAre you able to say whether you will be supporting cordova or capacitormany thanks\nDarren\nCode:"}, {"role": "assistant", "content": "Text:Hi @Shane_McAllister\nJust prompting on this query again. Are you guys making progress ? Any forward looking dates ? Are you using Cordova or Capacitor for the native interface ?\nthanks\nDarren\nCode:"}, {"role": "assistant", "content": "Text:Hi @Darren_Hunter - apologies for the delay - was on leave. Yes, we\u2019ve been making progress here and are aiming to release sample app and demos in September.\nCode:"}, {"role": "assistant", "content": "Text:thanks for the update - you didn\u2019t mention if your solution was using Cordova or Capacitor (or both maybe) - would you be able to let us know thanks\nCode:"}, {"role": "assistant", "content": "Text:Hi @Darren_HunterAttached you\u2019ll find an Ionic Web React App sample that uses Realm to login (you\u2019ll have to register a user). This looks like a Capacitor App. Developed by the Ionic team with our help. A blog post and a decent repo with instruction should follow, but wanted to give you something to work with.Hope this helps you.Google Drive file.\nCode:"}, {"role": "assistant", "content": "Text:@Darren_Hunter Ionic have published their Blog Building an app with Ionic React and Realm - Ionic Blog - and we will be following up shortly with taking this further to iOS & Android\nCode:"}, {"role": "assistant", "content": "Text:We should be in a position to publish this blog next week.\nCode:"}, {"role": "assistant", "content": "Text:Any plans to add Ionic Vue and Realm?\nCode:"}, {"role": "assistant", "content": "Text:Hi McAllister,Any news about Realm with Ionic?\nI searched the Blog and didn\u2019t find any publication as you indicated.\nIonic is a framework that hj runs under Angular, Vue and React, I hope the solution is universal and not just for React.\nI eagerly await information.\nThanks\nCode:"}, {"role": "assistant", "content": "Text:@Alan_Claudio_Melo1 Apologies - it got a little waylaid! But no fear, it\u2019s in final review and will be out very shortly.\nCode:"}, {"role": "assistant", "content": "Text:Looking forward to it.\nI have a project stopped, waiting for this solution.\nI don\u2019t want to use SQLite or another solution, Realm is perfect for use with MongoDB.I await brief news, thank you.\nCode:"}, {"role": "assistant", "content": "Text:Awesome to hear. However can you give and estimate of \u201cshortly\u201d. Is this days, weeks or months?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Gerald_Owens, Diego here, working on aforementioned postWe aim for it to be published this week, or next one. But take this with a grain of salt: this is a developer\u2019s estimation and you know\u2026Thanks for your patience and interest.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Duplicate data getting added into collection and tags: ['queries', 'node-js', 'data-modeling', 'mongoose-odm']"}, {"role": "user", "content": "Text:Hi, I have created a mongoose model as below, and set recordId field to \u201cunique: true\u201d to handle duplicate entry. But when through API multiple calls are happening within milliseconds the collection is allowing duplicate entries. Can anyone please tell how to handle this error.const RecordList = mongoose.model(\n\u2018record_list\u2019,\nmongoose.Schema({\nrecordId: {\ntype: String,\nunique: true,\nrequired: [true, \u2018Please enter record id!\u2019],\n},\ncampaign: {\ntype: String,\n}\n})\n);Thank You.\nCode:"}, {"role": "assistant", "content": "Text:Hello @Krushna_Chandra_Rout, Welcome to the MongoDB Community forum!With Mongoose ODM, when you create a field in a schema with property unique:true, it means that a unique constraint be created on that field. In fact it does create such an index in the database for that collection.For example, the following code creates such data and inserts one document. I can verify the collection, the document and the unique index from mongosh or Compass. In the shell, db.collection.getIndexes() prints the newly created index details.When I run the same program again, or try to insert another document with the same name: 'john', there is an error: MongoError: E11000 duplicate key error collection: test.records index: name_1 dup key: { name: \"john\" }.Please include the version of MongoDB and Mongoose you are working with.\nCode:unique:truemongoshdb.collection.getIndexes()name: 'john'MongoError: E11000 duplicate key error collection: test.records index: name_1 dup key: { name: \"john\" }const mongoose = require('mongoose');\nconst url = 'mongodb://127.0.0.1:27017/test';\nmongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });\n\nconst Schema = mongoose.Schema;\nvar RecordSchema = new Schema({\n name: { type: String, required: true, unique: true }\n}, { collection: 'records' })\n\nconst Record = mongoose.model('Record', RecordSchema);\n\nconst r1 = Record({ name: 'john' });\nr1.save(function(err) { \n\tif (err) throw err;\n\tconsole.log('r1 record saved.');\n});\n"}, {"role": "assistant", "content": "Text:But when through API multiple calls are happening within milliseconds the collection is allowing duplicate entriesThis may be that the index is created through Mongoose with background: true option. This option may not create the index immediately, and this allows duplicate entries on the indexed field.An option for you is to create the index from mongosh or Compass initially. You can still keep the Mongoose definition as it is. This will definitely trigger duplicate data error immediately.A quick query on my index data showed that the index is created with background:true option [*]:NOTE: This was with using Mongoose 6.2.4 and MongoDB v.5.0.6 (Atlas Cluster).\nCode:background: truemongoshbackground:true {\n \"v\" : 2,\n \"unique\" : true,\n \"key\" : {\n \"name\" : 1\n },\n \"name\" : \"name_1\",\n \"ns\" : \"test.records\",\n \"background\" : true // <---- [*]\n }\n"}, {"role": "user", "content": "Text:Hi, @Prasad_Saya Thank You for this solution.\nActually one of unique field was deleted from compass bymistakely that\u2019s why the above error was comming.Thank You.\nCode:"}, {"role": "assistant", "content": "Text:Actually one of unique field was deleted from compass bymistakelyThat is a bad situation. Database objects like collections, databases, indexes, etc., need to be carefully and securely managed.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Prasad_Saya ,\nI am having similar kind of issue. My operation is based on the last generated call on mongodb. I am generating a key in incremental order and for that I need to fetch the last generated key and then I am incrementing it based on last generated. Issue I am getting is when i hit the api in 0 sec for 50 keys the keys are not uniquely generated it points to the same thread. So is there any lock mechanism in mongodb to generate only one key at a time? Please suggest\nCode:"}, {"role": "assistant", "content": "Text:to fetch the last generated key and then I am incrementing it based on last generatedThe issue is that 2 or more processes/tasks/threads will read the same value and increment it to the same value and store back that same value. This is a typical issue in bad distributed system. This is not the way you do thing in a distributed system. You need to read and increment in a ACID way. It is not clear how you fetch the last generated key but if you do it with a sort in your collection then I do not know how you could do it. May be with a transaction. May be with repeating an upsert until you do not get a duplicate. One way to do without sort, it is to have the value in a collection and you use findOneAndUpdate to increment your value in an ACID way. But sorting or findOneAndUpdate is a big NO NO as it involves 2 or more server requests. Why don\u2019t you use an $oid, UUID, GUID?\nCode:"}, {"role": "assistant", "content": "Text:Hi @steevej ,\nThanks for the answer.\nWhy don\u2019t you use an $oid, UUID, GUID?\nActually, our requirement is that the alphanumeric key be generated once in a lifetime, never repeated and its size is 6 which will be later on incremented when the permutations will complete. I tried to lock the key using pessimistic locking, but I don\u2019t know if it\u2019s the correct way. According to the requirement, I am generating the key in incremental order using modulus operations I am dividing some incremental number/alphabets.size() to get the alphanumeric key of 6 digits in incremental order and it never repeats, where I need to have the last generated number. Can I use pessimistic locking?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Realm Sync vs Firestore Pricing and tags: ['atlas-device-sync']"}, {"role": "user", "content": "Text:I\u2019m considering using Realm Sync for a new project, but I\u2019m trying to understand if I\u2019m misunderstanding the pricing.If I understand the pricing (and that\u2019s a big \u201cif\u201d), Firestore seems a lot more economical. Unless I\u2019m missing something, the free tier seems far better on Firestore as well as the pricing after that (seems like it\u2019s half the cost of realm sync).Firebase Pricing\nhttps://cloud.google.com/firestore/pricingFirebase Prices for Requests\nReads $0.036 per 100,000 documents\nWrites $0.108 per 100,000 documents\nDelete $0.012 per 100,000 documentsData Storage = $0.108 / GB per monthLet\u2019s say that averages out to around 0.072 per 100,000 requests (excluding deletes)Realm Sync Pricing\nhttps://docs.mongodb.com/realm/billing/ $0.2 per 100,000 requests (effectively double if I\u2019m reading it correctly).\nPlus a sync cost of 0.00000008 / min.\nPlus data transfer = $0.12 / GBSeems like Realm double/triple charges for syncs (since it charges for the requests, sync time, and data transfer), and the cost per request being more than double than FirestoreI guess the biggest difference is with Firebase you\u2019re going to be paying a monthly fee for storage but I think the requests will be the most costly aspect of most apps (I could be wrong). Beyond that, Firestore isn\u2019t truly off-line first.Check out the examples for example mobile product cost:\nFirebase Example:\n\nScreen Shot 2021-08-16 at 10.48.32 AM720\u00d7780 74.6 KB\nRealm Example (go-to mobile application section on the Realm Pricing Page above as I\u2019m restricted in posting images or additional links)The costs per request seem to be the big differentiator. The free tier seems to be more generous with Firebase as well. Am I missing something or is Realm significantly more costly when compared with Firestore?\nCode:"}, {"role": "assistant", "content": "Text:Long time Firebase and Realm developer here\u2026I am not sure a comparison can be made between the two products as they serve different purposes.Realm is an offline first database and all of the app data is persisted locally and syncing in the background when necessary. On the other hand, Firebase is an online first database and data exists in the cloud* and sync\u2019s continually.So while you can compare some numbers, the bottom line is that if you\u2019re fetching Realm data that has already been sync\u2019d it\u2019s local and (essentially) $0 cost. Whereas if you\u2019re fetching Firebase data it will pull from the server at a cost.I would suggest evaluating how the app is going to be used - mostly offline first or online first and once you have clarity on that, comparing pricing would be more applicable.*while firebase offers offline persistence, it\u2019s designed for brief outages, like when a train disconnects as it goes through a tunnel.\nCode:"}, {"role": "assistant", "content": "Text:Firestore pricing is based on reads/writes per collection and Realm has it per request. Doesn\u2019t that make a big difference or am I missing something? From this point of view it seems that Firestore might be a lot more expensive if there is a need to read/write/delete multiple collections/documents.\nFor example - you want to execute query of 500 collections/documents.\nSo for Firestore this will count as 500 reads, but for Realm this will count as 1 request. Same goes for writes/deletes. Could you please confirm this?\nSo if this is correct, then it looks like Realm might be a lot cheaper when it comes to application that needs to query/modify/delete multiple collections/documents?\nCode:"}, {"role": "assistant", "content": "Text:On the other hand, Realm Sync pricing is strangely identical to AWS App Sync.About connection vs atomic change:\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: ServerSelectionTimeoutError [SSL: CERTIFICATE_VERIFY_FAILED] Trying to understand the origin of the problem and tags: ['python']"}, {"role": "user", "content": "Text:Hello, I am working on a python project using MongoDB for several months now, I had no connect issue until today where I encounter a CERTIFICATE_VERIFY_FAILED problem that looks like this:pymongo.errors.ServerSelectionTimeoutError: xxxx-shard-00-02.xxxxxx.mongodb.net:00000: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failedI browse through the community forums and lucky found the problem:My original code:My new fixed code:So it had something to do with the cacert.pem.But I find this problem odd, why today? it has been working for months with no issues, and furthermore, which cacert.pem is the default \u201cclient = pymongo.MongoClient(connection)\u201d using? Where is the problem originated from and how do I fix it at its core?I would very much appreciate it if someone explains this to me.Thank you.\nCode:connection = \"mongodb+srv://\"+ username + \":\" + password + \"@xxxx.xxxxx.mongodb.net/Configurations?retryWrites=true&w=majority\"\n\nclient = pymongo.MongoClient(connection)\nclient = pymongo.MongoClient(connection, ssl_ca_certs=certifi.where())\ncacert.pem"}, {"role": "assistant", "content": "Text:By default pymongo relies on the operating system\u2019s root certificates.But I find this problem odd, why today?It could be that Atlas itself updated its certificates or it could be that something on your OS changed. \u201ccertificate verify failed\u201d often occurs because OpenSSL does not have access to the system\u2019s root certificates or the certificates are out of date. For how to troubleshoot see TLS/SSL and PyMongo \u2014 PyMongo 4.3.3 documentationAlso please note that \u201cssl_ca_certs\u201d is deprecated and you should use \u201ctlsCAFile\u201d instead:\nCode:client = pymongo.MongoClient(connection, tlsCAFile=certifi.where())\n"}, {"role": "assistant", "content": "Text:thanks for sharing, currently still working in 2023!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Best index on aggregation with multiple match conditions and tags: ['aggregation', 'indexes']"}, {"role": "user", "content": "Text:I\u2019m trying to understand how the aggregation pipeline optimization works and what is the best index (or maybe more than one) to satisfy the following aggregation that have some optional stage with $match, based on user filter from UI, so it\u2019s like to have 4 four different queries to satisfy.I\u2019ve tried with some compound indexes and testing them with explain but I\u2019m not getting good results also on basic case (only first $match), maybe I have to rewrite some lines?\nCode:$match[{\n \"$match\": {\n \"__STATE__\": { \"$eq\": \"PUBLIC\" },\n \"countryCode\": {\n \"$exists\": true,\n \"$ne\": null\n }\n }\n },\n{\n \"$project\": {\n \"countryCode\": 1,\n \"createdAt\": 1,\n \"success\": 1\n }\n },\n//optional\n{\n \"$match\": {\n \"success\" : true\n }\n },\n//optional\n{\n \"$match\": {\n {\n \"$expr\": {\n \"$and\": [{\n \"$lte\": [\n \"$createdAt\",\n {\n \"$dateFromString\": {\n \"dateString\": \"#createdAtTo#\"\n }\n }\n ]\n }, {\n \"$gte\": [\n \"$createdAt\",\n {\n \"$dateFromString\": {\n \"dateString\": \"#createdAtFrom#\"\n }\n }\n ]\n }]\n }\n },\n]\n"}, {"role": "assistant", "content": "Text:Hi @Francesco_Fiorentino,The way to optimize aggregation pipelines is to try and minimize the amount of stags while pushing as much filtering as possible to the first stage. So if your optional stages can be added to the first stage this will be really helpful.In general indexing should have the order of Equality Range Sort when it comes to compound index placements.In your case I suggest to do an index on:And changed the projectiion to:Read this: Performance Best Practices: Indexing | MongoDB BlogThanks\nPavel\nCode:{ \"__STATE__\" : 1 , \"countryCode\": 1 , \"success\": 1 , \"createdAt\": 1}\n{\n \"$project\": {\n \"_id\" : 0,\n \"countryCode\": 1,\n \"createdAt\": 1,\n \"success\": 1\n }\n }\n"}, {"role": "assistant", "content": "Text:The courses M121 and M201 from https://university.mongodb.com are also very good resources in this regard.\nCode:"}, {"role": "assistant", "content": "Text:You can run explain and see how the pipeline gets transformed. Two things you can see from that:What we see is that you are using $expr for some reason and it\u2019s NOT as efficient as regular match expressions. If the format of createdAtFrom date string is \u201cnormal\u201d then it can just be passed to ISODate() constructor as right hand side of the comparison.Now, best index will always start with {__STATE__:1, countryCode:1, ... } since it seems like those are always filtered on, but the order of the other three fields depend on which filtering is more likely (and equality being ahead of range comparisons).Asya\nP.S. you don\u2019t need \"$exists\": true, since that\u2019s a strict subset of \"$ne\": null for countryCode in your query.\nCode:$exprcreatedAtFromISODate(){__STATE__:1, countryCode:1, ... }\"$exists\": true,\"$ne\": null"}, {"role": "user", "content": "Text:Thanks all for your suggests and sorry for my late response. I have already seen the suggested courses and tried to have more confidence with explain.\nThere are a couple of things not clear to me with this case:\nCode:explain{__STATE__:1, countryCode:1, ... }{__STATE__:1, createdAt:-1}"}, {"role": "assistant", "content": "Text:As always, please run explain(\"executionStats\") on the full aggregation and provide the output here - without seeing what the time is being spent on we would be guessing where the improvements could be best made.Asya\nP.S. if you are on 4.4 or later then full explain will show how much time is being spent in each stage of aggregation.\nCode:explain(\"executionStats\")"}, {"role": "user", "content": "Text:Following the entire explain output directly on production environment:}\nCode:{\n\"stages\" : [ \n {\n \"$cursor\" : {\n \"queryPlanner\" : {\n \"plannerVersion\" : 1,\n \"namespace\" : \"labid.outcomes\",\n \"indexFilterSet\" : false,\n \"parsedQuery\" : {\n \"$and\" : [ \n {\n \"__STATE__\" : {\n \"$eq\" : \"PUBLIC\"\n }\n }, \n {\n \"countryCode\" : {\n \"$not\" : {\n \"$eq\" : null\n }\n }\n }\n ]\n },\n \"queryHash\" : \"850416C8\",\n \"planCacheKey\" : \"58935625\",\n \"winningPlan\" : {\n \"stage\" : \"PROJECTION_SIMPLE\",\n \"transformBy\" : {\n \"success\" : true,\n \"createdAt\" : true,\n \"countryCode\" : true,\n \"_id\" : false\n },\n \"inputStage\" : {\n \"stage\" : \"FETCH\",\n \"filter\" : {\n \"countryCode\" : {\n \"$not\" : {\n \"$eq\" : null\n }\n }\n },\n \"inputStage\" : {\n \"stage\" : \"IXSCAN\",\n \"keyPattern\" : {\n \"__STATE__\" : 1,\n \"createdAt\" : -1\n },\n \"indexName\" : \"state_createdAt\",\n \"isMultiKey\" : false,\n \"multiKeyPaths\" : {\n \"__STATE__\" : [],\n \"createdAt\" : []\n },\n \"isUnique\" : false,\n \"isSparse\" : false,\n \"isPartial\" : false,\n \"indexVersion\" : 2,\n \"direction\" : \"forward\",\n \"indexBounds\" : {\n \"__STATE__\" : [ \n \"[\\\"PUBLIC\\\", \\\"PUBLIC\\\"]\"\n ],\n \"createdAt\" : [ \n \"[MaxKey, MinKey]\"\n ]\n }\n }\n }\n },\n \"rejectedPlans\" : [ \n {\n \"stage\" : \"PROJECTION_SIMPLE\",\n \"transformBy\" : {\n \"success\" : true,\n \"createdAt\" : true,\n \"countryCode\" : true,\n \"_id\" : false\n },\n \"inputStage\" : {\n \"stage\" : \"FETCH\",\n \"filter\" : {\n \"countryCode\" : {\n \"$not\" : {\n \"$eq\" : null\n }\n }\n },\n \"inputStage\" : {\n \"stage\" : \"IXSCAN\",\n \"keyPattern\" : {\n \"__STATE__\" : 1,\n \"success\" : 1\n },\n \"indexName\" : \"state_success\",\n \"isMultiKey\" : false,\n \"multiKeyPaths\" : {\n \"__STATE__\" : [],\n \"success\" : []\n },\n \"isUnique\" : false,\n \"isSparse\" : false,\n \"isPartial\" : false,\n \"indexVersion\" : 2,\n \"direction\" : \"forward\",\n \"indexBounds\" : {\n \"__STATE__\" : [ \n \"[\\\"PUBLIC\\\", \\\"PUBLIC\\\"]\"\n ],\n \"success\" : [ \n \"[MinKey, MaxKey]\"\n ]\n }\n }\n }\n }, \n {\n \"stage\" : \"PROJECTION_SIMPLE\",\n \"transformBy\" : {\n \"success\" : true,\n \"createdAt\" : true,\n \"countryCode\" : true,\n \"_id\" : false\n },\n \"inputStage\" : {\n \"stage\" : \"FETCH\",\n \"inputStage\" : {\n \"stage\" : \"IXSCAN\",\n \"keyPattern\" : {\n \"__STATE__\" : 1,\n \"countryCode\" : 1\n },\n \"indexName\" : \"state_countryCode\",\n \"isMultiKey\" : false,\n \"multiKeyPaths\" : {\n \"__STATE__\" : [],\n \"countryCode\" : []\n },\n \"isUnique\" : false,\n \"isSparse\" : false,\n \"isPartial\" : false,\n \"indexVersion\" : 2,\n \"direction\" : \"forward\",\n \"indexBounds\" : {\n \"__STATE__\" : [ \n \"[\\\"PUBLIC\\\", \\\"PUBLIC\\\"]\"\n ],\n \"countryCode\" : [ \n \"[MinKey, undefined)\", \n \"(null, MaxKey]\"\n ]\n }\n }\n }\n }\n ]\n },\n \"executionStats\" : {\n \"executionSuccess\" : true,\n \"nReturned\" : 2188033,\n \"executionTimeMillis\" : 8133,\n \"totalKeysExamined\" : 2189018,\n \"totalDocsExamined\" : 2189018,\n \"executionStages\" : {\n \"stage\" : \"PROJECTION_SIMPLE\",\n \"nReturned\" : 2188033,\n \"executionTimeMillisEstimate\" : 1909,\n \"works\" : 2189019,\n \"advanced\" : 2188033,\n \"needTime\" : 985,\n \"needYield\" : 0,\n \"saveState\" : 2279,\n \"restoreState\" : 2279,\n \"isEOF\" : 1,\n \"transformBy\" : {\n \"success\" : true,\n \"createdAt\" : true,\n \"countryCode\" : true,\n \"_id\" : false\n },\n \"inputStage\" : {\n \"stage\" : \"FETCH\",\n \"filter\" : {\n \"countryCode\" : {\n \"$not\" : {\n \"$eq\" : null\n }\n }\n },\n \"nReturned\" : 2188033,\n \"executionTimeMillisEstimate\" : 1437,\n \"works\" : 2189019,\n \"advanced\" : 2188033,\n \"needTime\" : 985,\n \"needYield\" : 0,\n \"saveState\" : 2279,\n \"restoreState\" : 2279,\n \"isEOF\" : 1,\n \"docsExamined\" : 2189018,\n \"alreadyHasObj\" : 0,\n \"inputStage\" : {\n \"stage\" : \"IXSCAN\",\n \"nReturned\" : 2189018,\n \"executionTimeMillisEstimate\" : 413,\n \"works\" : 2189019,\n \"advanced\" : 2189018,\n \"needTime\" : 0,\n \"needYield\" : 0,\n \"saveState\" : 2279,\n \"restoreState\" : 2279,\n \"isEOF\" : 1,\n \"keyPattern\" : {\n \"__STATE__\" : 1,\n \"createdAt\" : -1\n },\n \"indexName\" : \"state_createdAt\",\n \"isMultiKey\" : false,\n \"multiKeyPaths\" : {\n \"__STATE__\" : [],\n \"createdAt\" : []\n },\n \"isUnique\" : false,\n \"isSparse\" : false,\n \"isPartial\" : false,\n \"indexVersion\" : 2,\n \"direction\" : \"forward\",\n \"indexBounds\" : {\n \"__STATE__\" : [ \n \"[\\\"PUBLIC\\\", \\\"PUBLIC\\\"]\"\n ],\n \"createdAt\" : [ \n \"[MaxKey, MinKey]\"\n ]\n },\n \"keysExamined\" : 2189018,\n \"seeks\" : 1,\n \"dupsTested\" : 0,\n \"dupsDropped\" : 0\n }\n }\n }\n }\n },\n \"nReturned\" : NumberLong(2188033),\n \"executionTimeMillisEstimate\" : NumberLong(7433)\n }, \n {\n \"$group\" : {\n \"_id\" : \"$countryCode\",\n \"count\" : {\n \"$sum\" : {\n \"$const\" : 1.0\n }\n }\n },\n \"nReturned\" : NumberLong(203),\n \"executionTimeMillisEstimate\" : NumberLong(8120)\n }\n],\n\"serverInfo\" : {\n \"host\" : \"atlas-iddbm2-shard-00-01.ake5m.gcp.mongodb.net\",\n \"port\" : 27017,\n \"version\" : \"4.4.9\",\n \"gitVersion\" : \"b4048e19814bfebac717cf5a880076aa69aba481\"\n},\n\"ok\" : 1.0,\n\"$clusterTime\" : {\n \"clusterTime\" : Timestamp(1632748186, 1),\n \"signature\" : {\n \"hash\" : { \"$binary\" : \"er1V/UEDRoO+EvH/KZ5Nh2jjYWA=\", \"$type\" : \"00\" },\n \"keyId\" : NumberLong(6977486985841606664)\n }\n},\n\"operationTime\" : Timestamp(1632748186, 1)\n"}, {"role": "assistant", "content": "Text:2188033This query is aggregating over two million documents - even using an efficient index processing that many documents is going to take time. However here the best index isn\u2019t being used. It doesn\u2019t look like you have an index on the two fields you are querying on (STATE and countryCode).Asya\nCode:2188033"}, {"role": "user", "content": "Text:However here the best index isn\u2019t being used. It doesn\u2019t look like you have an index on the two fields you are querying on (STATE and countryCode).That index should be there, below the output of getIndexes() but it seems to be mentioned also on rejectedPlans: I didn\u2019t understand why it is not the winning one.This query is aggregating over two million documents - even using an efficient index processing that many documents is going to take time.This means, as I supposed previously, that on demand aggregation is not to be used in this case? What is the best approach to use? It is ok to set periodic aggregation with output on another collection or there is some approach more effective?\nCode:getIndexes()rejectedPlans[\n {\n \"v\" : 2,\n \"key\" : {\n \"_id\" : 1\n },\n \"name\" : \"_id_\"\n },\n {\n \"v\" : 2,\n \"key\" : {\n \"__STATE__\" : 1,\n \"createdAt\" : -1\n },\n \"name\" : \"state_createdAt\",\n \"background\" : false\n },\n {\n \"v\" : 2,\n \"key\" : {\n \"__STATE__\" : 1,\n \"success\" : 1\n },\n \"name\" : \"state_success\",\n \"background\" : true\n },\n {\n \"v\" : 2,\n \"key\" : {\n \"tagUid\" : 1\n },\n \"name\" : \"tagUid\",\n \"background\" : true\n },\n {\n \"v\" : 2,\n \"key\" : {\n \"__STATE__\" : 1,\n \"countryCode\" : 1\n },\n \"name\" : \"state_countryCode\"\n }\n]\n"}, {"role": "assistant", "content": "Text:The reason a different index wouldn\u2019t be used is it\u2019s not going to be much more selective - the country code matches in all but one thousand documents, indexes are most helpful when they are selective (i.e. narrow down the number of documents that match).ok to set periodic aggregation with output on another collectionThat\u2019s actually the best approach assuming you know most/many of the aggregations needed. Running aggregations periodically with output going into a \u201csummary\u201d collection is a long accepted way to reduce query time for most popular complex queries.Asya\nCode: \"nReturned\" : 2188033,\n \"totalKeysExamined\" : 2189018,\n \"totalDocsExamined\" : 2189018,\n"}, {"role": "assistant", "content": "Text:One thing that occurred to me is that you could simplify your pipeline a little to only $match on __STATE__ and then group on countryCode and then filter out _id being null. Filtering out records where countryCode is null or missing may be taking a lot more time/effort before $group (with minimal reduction in total records processed) when it would be very fast after\u2026Asya\nCode:$match__STATE__countryCode_idcountryCode$group"}, {"role": "assistant", "content": "Text:db.alerts.aggregate([ {\n$addFields: {\ntimestamp: {\n$toDate: \u201c$timestamp\u201d\n}\n}\n},\n{\n$match: {\ntimestamp: {\n$gte: new Date(Date.now() - 24* 60 * 60 * 1000),\n$lte: new Date()\n},\n}\n},{\n$facet: {\nTotal_log: [\nCode: { $count: \"Total_log\" }\n ] } }] ,{ allowDiskUse: true }).toArray();\nin this query i want to fetch data last 24 hour but it getting huge time to fetch and in my collection data approx 300 million so i use index also but it taking so much time\n"}, {"role": "assistant", "content": "Text:The $addFields needs to stream in memory all documents to convert them .As the match happens after it cannot use an index (data is already in agg memory.You need to filter on timestamp or have the documents with date values and not timestamps.Thanks\nPavel\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Multiple lookup in aggregate and tags: ['aggregation', 'data-modeling']"}, {"role": "user", "content": "Text:I have 4 collections, I want data from this collection for my Cart PageHere is the model of my collections\nUserCollection : { _id :1, cart:[{ itemsId:10 }], zipcode:{ userZipCodeId: 0000 } }ItemsCollection: [{ _id: 10, title: itemstitle }] ZipCodeCollection:[{ _id: 0000, placeName: NY,serviceProviders:[100,101,102] }] Providers :[ { _id: 100, title: Happy Store},{ _id: 101, title: ABC Store}]On my cart page, I want user cart Items data, check user Zipcode and search from ZipCodeCollection which are the service providers in the zip code, then get the provider info from the Provider collectionhere is my codehere it\u2019s working, but take more time ( more than seconds )to execute I am afraid about the performance and bad design, how to increase this code performance and design well\nCode:UserCollection : { _id :1, cart:[{ itemsId:10 }], zipcode:{ userZipCodeId: 0000 } }ItemsCollection: [{ _id: 10, title: itemstitle }] ZipCodeCollection:[{ _id: 0000, placeName: NY,serviceProviders:[100,101,102] }] Providers :[ { _id: 100, title: Happy Store},{ _id: 101, title: ABC Store}] \t\t\t User.aggregate([\n \t\t\t \t{ $match: { _id: req.user._id } },\n\n \t\t\t \t{\n \t\t\t \t\t$lookup:\n \t\t\t \t\t{\n\t\t \t\t\t \tfrom: 'ItemsCollection',\n\t\t \t\t\t \tlocalField: 'cart',\n\t\t \t\t\t \tforeignField: '_id',\n\t\t \t\t\t \tas : \"cartList\"\n\t \t\t\t\t},\n\t \t\t\t},\n\n\n\t\t\t\t {\n\n \t\t\t \t\t$lookup:\n \t\t\t \t\t{\n\t\t \t\t\t \tfrom: 'zipcode',\n\t\t \t\t\t \tlocalField: 'zipcode.userZipCodeId',\n\t\t \t\t\t \tforeignField: '_id',\n\t\t \t\t\t \tas : \"zipcodeList\"\n\n\t \t\t\t\t},\t \t\n\t \t\t\t},\n\n\t \t\t\t{\n \t\t\t \t\t$lookup:\n \t\t\t \t\t{\n\t\t \t\t\t \tfrom: 'providers',\n\t\t \t\t\t \tlocalField: 'zipcodeList.providers',\n\t\t \t\t\t \tforeignField: '_id',\n\t\t \t\t\t \tas : \"providersList\"\n\n\t \t\t\t\t},\t\t \t\t\t\t\n\t \t\t\t},\n\t\n\t\t\t\t{\"$match\":{\"providersList.status\": true }},\n\t\t\t\t{\n\t\t\t\t\t$project:\n\t\t\t\t\t{\n\t\t\t\t\t\t_id:1,\n\t\t\t\t\t\tpincode:1,\n\t\t\t\t\t\temail:1,\n\t\t\t\t\t\tname:1,\n\t\t\t\t\t\tcartList:1,\n\t\t\t\t\t\tzipcodeList:1,\n\t\t\t\t\t\tcartList:1\n\n\t\t\t\t\t}\n\t\t\t\t}\t\n"}, {"role": "assistant", "content": "Text:Hi @david_jk and welcome in the MongoDB Community !Congratulation for finding and trying to eradicate\u2500before it actually happened\u2500the MongoDB #1 trap !You actually answered your problem yourself: it\u2019s a terrible data model and this will result in terrible performance.The only way to fix this is to fix the data model.I highly recommend that you take the time to read the above doc and especially try to check the 2 talks at the bottom + the white paper.Your current data model looks like an SQL design. In MongoDB, data that is read together, should be stored together so $lookup is actually a very last resort.In your case here, Users and Items are most probably the only 2 real collections. The 2 others should be embedded and the entries eventually be duplicated across the different documents.Also, there are a few design pattern that could be helpful.For this, I recommend you have a look to:And in your case, I think you could benefit from the Extended Reference Pattern:\nimage842\u00d7774 179 KB\nIn your user cart, you would store the list of items IDs and quantities, but probably also a few other fields like the price, label and description for example.\nSo for example, when you open the cart in your app, you don\u2019t need to $loopup the items because all the information you need is already in your user cart items. If the user clicks on an item to get more details about it (length, height, weight, technical specs\u2026), then you can fetch directly (findOne) the details of that item. In the end, you might not even need $lookup at all.A comment though\u2026 Usually the carts are stored in a separated collection so they can benefit from a TTL index (cart expiration 30 min).Nothing of what I have said here is the absolute and unique truth. It\u2019s all about your use cases and queries. Find these first. They will help design your documents.A quick example. Let\u2019s say I have a collection of books and authors.\nIf I\u2019m a bookstore, then authors should be embedded in books because my queries are all manipulating books before anything else.\nIf I\u2019m creating Wikipedia for famous authors. Then it\u2019s the opposite. Books should be embedded in my authors documents because they are just a detail in this system.\nAnd depending on the cardinality of both, it could also be a valid choice to keep them separated and maintain mono or bi-directional references.Schema design is an art . The reward is premium performances.Cheers,\nMaxime.\nCode:$lookupUsersItems$loopupfindOne$lookup"}, {"role": "assistant", "content": "Text:Thanks for the reply and the resources links. I am facing the same issue and will benefit from your answer.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to connect to mongodb on remote server from spring boot? and tags: ['java', 'spring-data-odm']"}, {"role": "user", "content": "Text:I have a Spring boot application configured wih MongoDB.Everything worked just fine when working with mongodb on localhost.The problem is when i try to connect to mongodb on remote server i get \u201cException opening socket\u201d and \u201cconnect timed out\u201d.\nI already changed bind_ip = 127.0.0.1 to bind_ip = 0.0.0.0.\nThis is the config in my application.properties file:\nspring.data.mongodb.uri=mongodb://user:password@remote_url/database_name\nCode:"}, {"role": "assistant", "content": "Text:Is it a replica or a standalone DB?\nWhat does you remote url look likeSample from mongo doc\nspring.data.mongodb.uri=mongodb://user:password@mongo1.example.com:12345,mongo2.example.com:23456/test\nCode:"}, {"role": "user", "content": "Text:how can i identify if it\u2019s a replica or a standalone ?\nCode:"}, {"role": "assistant", "content": "Text:Can you access your remote db from shell?You can use rs.status(),rs.conf() to know about your setup\nCode:"}, {"role": "user", "content": "Text:rs.status\nfunction() {\nreturn db._adminCommand(\u201creplSetGetStatus\u201d);\n}\nrs.conf()\nuncaught exception: Error: Could not retrieve replica set config: {\n\u201cok\u201d : 0,\n\u201cerrmsg\u201d : \u201cnot running with --replSet\u201d,\n\u201ccode\u201d : 76,\n\u201ccodeName\u201d : \u201cNoReplicationEnabled\u201d\n} :\nrs.conf@src/mongo/shell/utils.js:1599:11\n@(shell):1:1\nCode:"}, {"role": "assistant", "content": "Text:Hi, did you ever solve the problem? I have the same issue. How did you fix it?\nCode:"}, {"role": "assistant", "content": "Text:Are you using correct host & port?\nIs your mongodb running with auth?\nIs it standalone or replica\nCheck this link for various connect strings\nCode:"}, {"role": "assistant", "content": "Text:Sorry for taking so long to respond. If I am using a URI, then I thought I\u2019m not supposed to configure a host and port on the application,properties file? No it is not running with auth. Essentially, I have successfully connected to MongoDB Compass with no problems, but when I try to set up the applications.properties file to connect to MongoDB Atlas, I have errors. I get the exact same error: \u201cException opening socket\u201d and \u201cconnect timed out\u201d. Do you have any advice on how to configure a Java Springboot application to connect to MongoDB Atlas if I have been trying the URI method, and I\u2019ve enabled all IP\u2019s to be able to access my database.\nCode:"}, {"role": "assistant", "content": "Text:Can you connect by shell?\nWhat type of connect string are you using in URI?\nSRV or long form(old style)\nWith long form you have to use port\nCheck our forum threads.Many examples given for application.properties\nCode:"}, {"role": "assistant", "content": "Text:Hello, thanks for your help. I finally figured it out. The wifi was the problem, and it works on my personal mobile hotspot.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Why do we need alias=_id in pydantic model of fastapi? and tags: ['python']"}, {"role": "user", "content": "Text:From Getting Started with MongoDB and FastAPI | MongoDB, this pydantic model has id field with alias _id.Can someone more clearly explain the datatypes at each stage of the request/response data transformation pipeline? (Pydantic(fastapi) \u2194 pymongo driver \u2194 mongodb )\nI\u2019m not sure which stage expects/produces id and which stage expects/produces _id, and why the api should accept both id and _id.\nI\u2019m also confused about 3 cases when is id designed to bewhich the article wasn\u2019t clear at explaining during the alias section.That article says We set this id value automatically to an ObjectId string, so you do not need to supply it when creating a new student.\nDoes this mean the alias of _id only comes into play when someone calls fastapi endpoint and provided an _id in body of post request, so it doesn\u2019t have to be automatically created by pydantic?Is case 1 and 2 above even relevant when working with fastapi (when users interact only with the api)?\nThe article says \u201cwhen creating a new student\u201d. What happens if I had already inserted the data directly through mongo shell or driver (meaning not going through pydantic), and I only use fastapi to read data, does this mean this whole id aliasing thing can be ignored?\nFurthermore, does it also mean I don\u2019t even have to make any pydantic models if i only want to write a read-only fastapi?\nCode:id_idallow_population_by_field_name = Trueclass StudentModel(BaseModel):\n id: PyObjectId = Field(default_factory=PyObjectId, alias=\"_id\")\n name: str = Field(...)\n email: EmailStr = Field(...)\n course: str = Field(...)\n gpa: float = Field(..., le=4.0)\n\n class Config:\n allow_population_by_field_name = True\n arbitrary_types_allowed = True\n json_encoders = {ObjectId: str}\n schema_extra = {\n \"example\": {\n \"name\": \"Jane Doe\",\n \"email\": \"jdoe@example.com\",\n \"course\": \"Experiments, Science, and Fashion in Nanophotonics\",\n \"gpa\": \"3.0\",\n }\n }\nid_idWe set this id value automatically to an ObjectId string, so you do not need to supply it when creating a new student._id"}, {"role": "assistant", "content": "Text:Hi @Han_N_A and welcome to the forums!What is the significance of this alias?In MongoDB, a document must have a field name _id. This is reserved for use as a primary key; its value must be unique in the collection, and is immutable. See also MongoDB Field Names. While in Pydantic, the underscore prefix of a field name would be treated as a private attribute. The alias is defined so that the _id field can be referenced.The StudentModel utilises _id field as the model id called id. This means, whenever you are dealing with the student model id, in the database this will be stored as _id field name instead.Must allow_population_by_field_name = True be added for this alias to be used to intended effect or having default False works too?Depends on the application use case. If the application needs to be able to accept id input in the creation, then yes. Otherwise, if the application will just create id value automatically then you can set this to False.The reason why allow_population_by_field_name is True, is so that the application can accept a student model creation with id field. If you were to set this option to False, a field value of id input will be ignored in the creation of student model. i.e. in def create_student().I\u2019m not sure which stage expects/produces id and which stage expects/produces _id , and why the api should accept both id and _id.Although the API accepts _id because of the alias, you should just use id throughout the application. The clients that consumes the API would likely need to handle _id in the JSON response.and I only use fastapi to read data, does this mean this whole id aliasing thing can be ignored?You would need the alias to translate id to _id as a typed return, but you won\u2019t need the allow_population_by_field_name (default False)Furthermore, does it also mean I don\u2019t even have to make any pydantic models if i only want to write a read-only fastapi?You can use FastAPI without Pydantic models and just utilise Body. See FastAPI without PydanticRegards,\nWan.\nCode:_id_idStudentModel_ididid_idallow_population_by_field_name = TrueididFalseallow_population_by_field_nameTrueidFalseidid_id_idid_idid_idallow_population_by_field_nameFalse"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongorestore error encountered server selection timeout and tags: ['database-tools', 'backup']"}, {"role": "user", "content": "Text:Hi ,Just wanted to ask regarding mongorestore error that i encountered ,\" error connecting to host: could not connect to server: server selection error: server selection timeout, current topology: { Type: Single, Servers: [{ Addr: 127.0.0.1:37027, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : connection(127.0.0.1:37027[-61]) incomplete read of message header: EOF }, ] }\"command usedmongorestore -h 127.0.0.1 --gzip --archive=/home/mongodbadm/advisory_dump.gz --port 37027 -u testuser -p \u2018testpassw\u2019 --authenticationDatabase adminthe dump only contains a specific database.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Daniel_Inciong,It looks like no process is listenning on 127.0.0.1:37027\u2026Can you verify that this is actually the correct port and host?Try a mongo shell connection to verify\u2026Additionally, what is the mongorestore version and the server version on 37027 port?Best regards,\nPavel\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: TypeError: Cannot read properties of undefined (reading 'startsWith') and tags: []"}, {"role": "user", "content": "Text:I have this code here:but it is giving me this error here:TypeError: Cannot read properties of undefined (reading 'startsWith')What do you think it could be wrong?I am using this code for Nextjs\nCode:import { MongoClient } from \"mongodb\";\n\nconst createConnection = () => {\n\n // let current = null;\n\n const client = new MongoClient(process.env.MONGODB_URI);\n\n return async function run() {\n\n await client.connect();\n\n };\n\n};\n\nexport const managerdb = createConnection();\nTypeError: Cannot read properties of undefined (reading 'startsWith')"}, {"role": "user", "content": "Text:\nCapture111359\u00d7770 46.3 KB\n\nCode:"}, {"role": "assistant", "content": "Text:I am node a node.js guy, but perhaps MONGODB_URI is not defined\nCode:"}, {"role": "assistant", "content": "Text:The name startsWith looks like a field from a $graphLookup stage.I suspect that you have some logic error in the code that generates a dynamic $graphLookup with a null object.I have doubts that the issue is in the connect code you shared.\nCode:"}, {"role": "user", "content": "Text:The URI is good\u2026 tested and got connection OK from another file app code.This error is trigger from a page requesting the connection from the utils page\u2026\nCode:mport { managerdb } from \"../utils/connect\";\n\nexport const getStaticProps = async () => {\n\n const { db } = await managerdb.connect();\n\n const data = await db\n\n .collection(\"parts\")\n\n .find({})\n\n .sort({})\n\n .limit(1000)\n\n .toArray();\n\n return {\n\n props: {\n\n data: JSON.parse(JSON.stringify(data)), // why?\n\n },\n\n revalidate: 60,\n\n };\n\n};\n"}, {"role": "assistant", "content": "Text:The more I think about that issue the less confident I feel about my $graphLookup thing. If there was an issue with it, I suspect you would get a server error rather than a type error.DespiteThe URI is good\u2026 tested and got connection OK from another file app codeIt would be helpful to see that URI since some application do not use exactly the same format.\nCode:"}, {"role": "assistant", "content": "Text:A post was split to a new topic: Cannot read properties of undefined (reading \u2018type\u2019)\nCode:"}, {"role": "assistant", "content": "Text:\nCode:Error: Cannot read properties of undefined (reading 'connection')\n[nodemon] app crashed - waiting for file changes before starting...\n\nconst mongoose = require(\"mongoose\");\nconst connectDB = async () => {\n const conn = await mongoose\n .connect(process.env.MONGO_URI, {\n useNewUrlParser: true,\n useUnifiedTopology: true,\n })\n .catch((err) => {\n console.log(\"error: \", err);\n });\n\n console.log(`Mongoose Connected: ${conn.connection.host}`.cyan.underline.bold);\n};\n\nmodule.exports = connectDB;\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: $count and $sort inside $search and tags: ['atlas-search', 'text-search']"}, {"role": "user", "content": "Text:Hello!\nI believe having the $count and $sort inside $search has been asked by lot of people.\nWanted to know how others are doing it until the feature is provided.\nI am observing high memory usage by doing $count and $sort after the $search. If there are 2 different processes mongot for $search and mongod for $count and $sort what is causing this high memory?\nAny ideas?Best,\nSupriya\nCode:"}, {"role": "assistant", "content": "Text:Hi again @Supriya_Bansal!Customers are using the near operator to sort numeric results today. Most search use cases want to be sorted by relevance, so near influences relevance based on numeric order. However, if you want an absolute sort, you can boost the near clause with an arbitrarily high number like:We are releasing a search optimized count operator in a couple months, and search optimized sort soon after.\nCode:near{\n $search: {\n \"compound\": {\n \"must\": [\n {\n \"text\": {\n \"query\": \"Adam\",\n \"path\": \"A\"\n }},\n {\n \"range\": {\n \"gt\":0,\n \"lt\":12,\n \"path\": \"B\"\n }},\n {\n \"near\": {\n \"path\": \"B\",\n \"origin\":12,\n \"pivot\": 1,\n \"score\": { \"boost\": { \"value\": 999} }\n }\n }\n ]\n }\n }\n}\n"}, {"role": "user", "content": "Text:Thanks @Marcus!\nI am using the \u201cwildcard\u201d operator and our clients want the results to be sorted alphabetically.\nWould you have an example?\nCode:"}, {"role": "assistant", "content": "Text:We don\u2019t support that today using the $search operator alone. It is coming soon.\nCode:$search"}, {"role": "user", "content": "Text:Thank you @Marcus for the update!!\nCode:"}, {"role": "assistant", "content": "Text:@Marcus Still struggling with counting search result after full text search. A strange behavior I noticed is when I search for a query \u201charry potter\u201d it counts fast as compare to \u201cthe harry potter\u201d. What difference \u201cthe\u201d makes in query which make it too slow.\nAny solution?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Marcus, this there an update on this? Or has it been released yet?\nCode:"}, {"role": "user", "content": "Text:$count with $search is now available. Still waiting on the $sort inside $search.\nCode:"}, {"role": "assistant", "content": "Text:Hey @Marcus, any update regarding $sort inside $search? In my use case not having $sort available inside $search will heavily affect performance\nCode:"}, {"role": "assistant", "content": "Text:@Marcus Any idea when faster sort will be coming to atlas search? stored source fields do not provide the speed that is acceptable.\nCode:"}, {"role": "assistant", "content": "Text:My use case would also benefit from \u201csearch optimized sort\u201d. I\u2019ll check back here and the changelog for any updates. Is this feature still coming soon?\nCode:"}, {"role": "assistant", "content": "Text:@Elle_Shwer @Andrew_Davidson could you provide any ETA on \u201csearch optimized sort\u201d coming to the platform? What is the best place to read about upcoming features?\nCode:"}, {"role": "assistant", "content": "Text:We will keep our Feedback Portal and the changelog you linked up to date. Changelog most reliably.@Daniel_Beaulieu, if this is a challenge for you, do you mind sharing the following information:\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m implementing paging/sorting on a multi-tenant collection. Any reasonable filter on top of the full data set where results are in the tens or low thousands performs very will. Worst case is there is no filter (other than tenantId filter that gets added automatically). In this case, 750k total documents takes 43 seconds. I\u2019m happy to provide more info or get on a call to discuss more, but figured i\u2019d post what i have collected so far.\nCode:db.mycollection.aggregate(\n [\n {\n $search: {\n index: \"default\",\n returnStoredSource: true,\n count: {\n type: \"total\",\n },\n compound: {\n must: [\n {\n text: {\n query: \"60140fae076eeb001176245c\",\n path: \"tenantId\",\n },\n },\n ],\n },\n },\n },\n {\n $sort: { displayName: 1 },\n },\n {\n $facet: {\n totalCount: [\n { $limit: 1 },\n { $project: { meta: \"$$SEARCH_META\" } },\n { $group: { _id: null, count: { $sum: \"$meta.count.total\" } } },\n ],\n results: [\n { $skip: 0 },\n { $limit: 10 },\n {\n $lookup: {\n from: \"mycollection\",\n localField: \"_id\",\n foreignField: \"_id\",\n as: \"document\",\n },\n },\n {\n $unwind: {\n path: \"$document\",\n },\n },\n {\n $replaceRoot: {\n newRoot: \"$document\",\n },\n },\n ],\n },\n },\n ],\n {\n allowDiskUse: true,\n }\n);\n\n"}, {"role": "assistant", "content": "Text:43 seconds with Stored Source? And what is your ideal response time?\nCode:"}, {"role": "assistant", "content": "Text:Yes, 43 seconds is with stored source. The ideal performance is at least the same as non $search based that uses normal mongo index. This runs in 6 seconds.\nCode:db.mycollection.aggregate([\n {\n $match: {\n tenantId: '60140fae076eeb001176245c'\n }\n },\n {\n $sort: {\n displayName: 1\n }\n },\n {\n $facet: {\n results: [{$skip: 0}, {$limit: 10}],\n total: [{$group: {_id: null, count: { $sum: 1 }}}]\n }\n }\n])\n"}, {"role": "assistant", "content": "Text:Thanks for the response, may respond directly but in the mean time our team is evaluating this. Improving the performance for pagination and sort are extremely top of mind for us at the moment.\nCode:"}, {"role": "assistant", "content": "Text:@Marcus could you please tell me how we can use sort inside the $search pipeline?\nCode:"}, {"role": "assistant", "content": "Text:seems to be not possible right now, only can sort after search, which is slow\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Query nested objects in a document with unknown key and tags: ['queries']"}, {"role": "user", "content": "Text:Hi,I have a collection with many documents that do have a \u201citem\u201d property where the value is an object with key-value-pairs:Now I try to query all objects that have an item with \u201cLastEvent\u201d being \u201cOn\u201d but I can\u2019t find a way how to do that.I can find many examples to query nested arrays but not a dictionary like structure with key value pairs.\nOnly thing I found was aggregating and using objectToArray before matching but that sounds like a huge performance impact and it\u2019s pretty hard to get done with C#. Is there no way to do something like \u201citem.*.LastEvent\u201d: \u201cOn\u201d?\nCode:{\n \"_id\" : ObjectId(\"60054d3e20b5c978eb93bb7f\"),\n\t\"items\": {\n\t\t\"o1n2rpon12prn\": {\n\t\t\t\"LastEvent\": \"On\"\n\t\t},\n\t\t\"sdbqw12f12f\": {\n\t\t\t\"LastEvent\": \"Off\"\n\t\t},\n\t\t\"yxvcaqeg23g23g\": {\n\t\t\t\"LastEvent\": \"Error\"\n\t\t}\n\t}\n}\n"}, {"role": "assistant", "content": "Text:It will be hard to achieve something with the schema. I would consider using Building with Patterns: The Attribute Pattern | MongoDB Blog.You can then have a multi-keys index on items.k and with $elemMatch (or $unwind and $match) you can find the k for which LastEvent:On.Just the names o1n2rpon12prn, sdbqw12f12f and yxvcaqeg23g23g gives me the feeling that they should be values rather than keys.\nCode:{\n \"_id\" : ObjectId(\"60054d3e20b5c978eb93bb7f\"),\n\t\"items\": [\n\t\t{ \"k\" : \"o1n2rpon12prn\" ,\n\t\t\t\"LastEvent\": \"On\"\n\t\t},\n\t\t{ \"k\" : \"sdbqw12f12f\" ,\n\t\t \"LastEvent\": \"Off\"\n\t\t},\n\t\t{ \"k\" : \"yxvcaqeg23g23g\",\n\t\t \"LastEvent\": \"Error\"\n\t\t}\n\t]\n}\n"}, {"role": "user", "content": "Text:Thank you for the answer The keys are unique and basicly the id of the item (in my case they were just examples but they are based on UUIDs in reality).I was thinking about using an array and adding the key as an id field, but I found it hard to update the correct item later. I have multiple services that access the same database and add different values to the same \u201ckey\u201d (sometimes even simultaneously). For example one adds/updates the \u201cLastEvent\u201d field and another service adds/updates a \u201cCurrentState\u201d field. Currently it works very easy by using an upsert and a simple set on \u201citem.id.LastEvent\u201d and the different services don\u2019t interfere. If the key isn\u2019t there yet it will just be created.\nWith arrays it seems to be much harder to upsert data into the array depending on a key or field inside the array.\nI think I could do something similar for existing values by filtering for the item id and then using \u201citems.$.LastEvent\u201d to update that object, but the filter won\u2019t work if there is no such object yet and with upsert it will just create a whole new document then.On stackoverflow I found that question and the answers there is to use objects\u2026but then I\u2019m back here.\nnode.js - Can mongo upsert array data? - Stack OverflowAs multiple services might work on the same document I also can\u2019t use two calls (pull and update).I also thought about using separate documents for the items but then my problem is that I\u2019ve a retention policy set for this collection and I then need to figure out a way to remove the other documents aswell.As a workaround I\u2019m now using an aggregate pipeline similar to that:But I\u2019m a bit worried about performance as I might have a huge count of documents\nCode:[\n {$addFields:{u:{$objectToArray:\"$items\"}}},\n {$match:{\"u\":{$elemMatch: { \"v.LastEvent\": \"On\" }}}},\n {$project:{u:0}}\n]\n"}, {"role": "assistant", "content": "Text:Hi @Wolfspirit,Have you considered using a text index where you will index all items like { 'items.$**' : \"text\" }Than query :Or aggregate with text search and later on filter with $map.Thanks\nPavel\nCode:{ 'items.$**' : \"text\" } db.stores.find( { $text: { $search: \"On\" } } )\n"}, {"role": "assistant", "content": "Text:Since I am not familiar with such indexes, I go ahead and try it.I reach an hurdle at creating the index:{ 'items.$**' : \"text\" }I got:Creating the index as given at https://docs.mongodb.com/manual/core/index-text/ worked:However, db.search.find( { $text: { $search: \"On\" } } ) gives no result despite:Both mongo and mongod are 4.0.5 on Arch Linux.I guess I miss something.\nCode:{ 'items.$**' : \"text\" }mongo localhost> db.search.createIndex( { 'items.$**' : \"text\" } )\n{\n\t\"ok\" : 0,\n\t\"errmsg\" : \"Index key contains an illegal field name: field name starts with '$'.\",\n\t\"code\" : 67,\n\t\"codeName\" : \"CannotCreateIndex\"\n}\nmongo localhost> db.search.createIndex( { '$**' : \"text\" } )\n2021-01-19T08:24:52.091-0500 I INDEX [conn8] build index on: test.search properties: { v: 2, key: { _fts: \"text\", _ftsx: 1 }, name: \"$**_text\", ns: \"test.search\", weights: { $**: 1 }, default_language: \"english\", language_override: \"language\", textIndexVersion: 3 }\n2021-01-19T08:24:52.091-0500 I INDEX [conn8] \t building index using bulk method; build may temporarily use up to 500 megabytes of RAM\n2021-01-19T08:24:52.094-0500 I INDEX [conn8] build index done. scanned 1 total records. 0 secs\n{\n\t\"createdCollectionAutomatically\" : false,\n\t\"numIndexesBefore\" : 1,\n\t\"numIndexesAfter\" : 2,\n\t\"ok\" : 1\n}\ndb.search.find( { $text: { $search: \"On\" } } )mongo localhost> db.search.find().pretty()\n{\n\t\"_id\" : ObjectId(\"60054d3e20b5c978eb93bb7f\"),\n\t\"items\" : {\n\t\t\"o1n2rpon12prn\" : {\n\t\t\t\"LastEvent\" : \"On\"\n\t\t},\n\t\t\"sdbqw12f12f\" : {\n\t\t\t\"LastEvent\" : \"Off\"\n\t\t},\n\t\t\"yxvcaqeg23g23g\" : {\n\t\t\t\"LastEvent\" : \"Error\"\n\t\t}\n\t}\n}\n"}, {"role": "assistant", "content": "Text:Hi @steevej and @Wolfspirit,Sorry I might confused Wild Card index syntax and text index and thought items.$** is acceptable.Now @steevej, you have hit an edge case with your search for the word \u201con\u201d . The problem is that this word is considered a stop word like \u201cand\u201d,\u201cor\u201d and \u201cthe\u201d etc.Therefore it is not indexed If you remove the default english and specifiy \u201cnone\u201d they will:Now it returns a result:Please let me know if you have any additional questions.Best regards,\nPavel\nCode:items.$**db.search.createIndex( { '$**' : \"text\" },{ default_language: \"none\" , language_override : \"none\"} )\n db.search.aggregate([{$match : { $text: { \"$search\": \"on\" } }}])\n{ \"_id\" : ObjectId(\"60054d3e20b5c978eb93bb7f\"), \"items\" : { \"o1n2rpon12prn\" : { \"LastEvent\" : \"On\" }, \"sdbqw12f12f\" : { \"LastEvent\" : \"Off\" }, \"yxvcaqeg23g23g\" : { \"LastEvent\" : \"Error\" } } }\n"}, {"role": "assistant", "content": "Text:Thanks, I learned a lot.\nCode:"}, {"role": "assistant", "content": "Text:Hello Steevej, is there any way to search the key in your reference if the key is already know ?any suggestion will save a day. \nCode:"}, {"role": "assistant", "content": "Text:I do not understand your question.It is an old thread. Please start a new one.Provide sample documents, the queries and expected results.\nCode:"}, {"role": "assistant", "content": "Text:I am asking if we provide the text value for searching it will search and return the document . is there any way to find the key for ex below document :- is there any way to search o1n2rpon12prn value and return all the document which contains this value:- I am reading your last year previous post so thought I can ask here only. sorry for the statement, I am not a good writer.\n{\n\u201c_id\u201d : ObjectId(\u201c60054d3e20b5c978eb93bb7f\u201d),\n\u201citems\u201d : {\n\u201co1n2rpon12prn\u201d : {\n\u201cLastEvent\u201d : \u201cOn\u201d\n},\n\u201csdbqw12f12f\u201d : {\n\u201cLastEvent\u201d : \u201cOff\u201d\n},\n\u201cyxvcaqeg23g23g\u201d : {\n\u201cLastEvent\u201d : \u201cError\u201d\n}\n}\n}\nCode:"}, {"role": "assistant", "content": "Text:see MongoDB Courses and Trainings | MongoDB University\nCode:db.collection.find( { \"items.o1n2rpon12prn.LastEvent\" : \"On\" } )\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Error: {\"message\":\"'remove' is not a function\",\"name\":\"TypeError\"} and tags: ['queries', 'atlas-functions']"}, {"role": "user", "content": "Text:Hello, Query we are firing from Atalas Trigger.\nAtlas version: \t4.4.18Trigger:Error:{\u201cmessage\u201d:\"\u2018remove\u2019 is not a function\",\u201cname\u201d:\u201cTypeError\u201d}Logs:[ \u201c2022-11-6\u201d, \u201c26200\u201d ]\nCode:exports =async function() {\n\tlet collections = context.services.get(\"XYZZZ\").db(\"XXXXX\");\n\tlet orderhistoryCollection = collections.collection(\"XXXXXX\");\n\tconst pipeline =[\n\t{\n $match: {\n creationDate: {\n $ne: \"\",\n }\n }\n },\n {\n $addFields: {\n created_at: {\n $toDate: \"$creationDate\",\n },\n },\n },\n {\n $match:{\n \"created_at\":{$lt:new Date(getThreshholdDate())}\n},\n },\n {\n $project: {\n _id: \"$_id\"\n\n },\n },\n];\nconst idList = await orderhistoryCollection.aggregate(pipeline).toArray();\n\nconsole.log(\"No of documents deleted: \"+idList.length);\n//console.log(idList);\nif(idList.length>0){\norderhistoryCollection.remove({ _id: { $in: idList } });\n}\nreturn idList;\n \n}\n\nfunction getThreshholdDate() {\n let date = new Date();\n date.setMonth( date.getMonth() - 7 );\n console.log(date.getFullYear()+\"-\"+date.getMonth()+\"-\"+date.getDate());\n return date;\n}\n\n"}, {"role": "assistant", "content": "Text:Perhaps you want deleteMany rather than remove?\nCode:deleteManyremove"}, {"role": "user", "content": "Text:Changed the code to deleteMany but it is not deleting records. Am I missing something?ran on Fri Jan 06 2023 12:56:03 GMT-0600 (Central Standard Time)\ntook 4.528895883s\nlogs:\n2022-5-6\nNo of documents to be deleted: 50000\nDeleted 0 documents\nCode:console.log(\"No of documents to be deleted: \"+idList.length);\nif(idList.length>0){\n const deleteResult = await orderhistoryCollection.deleteMany({ _id: { $in: idList } });\n console.log(\"Deleted \" + deleteResult.deletedCount + \" documents\");\n}\n\n"}, {"role": "assistant", "content": "Text:What is the output of:N.B.: Depending on how/where you call this, you may need await, etc.\nCode:console.log(orderhistoryCollection.find({ _id: { $in: idList } }).count());\nawait"}, {"role": "user", "content": "Text:Fixed issue with this code change\nCode:const idList = await orderhistoryCollection.aggregate(pipeline).toArray();\nconsole.log(\"No of documents to be deleted: \"+idList.length);\n\nif(idList.length>0){\n try{\n let ids=[];\n idList.forEach(doc=>ids.push(doc._id));\n const deleteResult = await orderhistoryCollection.deleteMany({ _id: { $in: ids } });\n console.log(\"Deleted \" + deleteResult.deletedCount + \" documents\");\n }\n catch(e)\n {\n console.log(e);\n }\n}\n"}, {"role": "assistant", "content": "Text:Please Use deleteOne() Instead remove() function. If you want to delete single item deleteOne( ) & if there ary many documents there please use other delete Options.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Installation of MongoDb on Ubuntu 22.04 and tags: []"}, {"role": "user", "content": "Text:Hello.I am trying to install Mongodb in Ubuntu22.04 but it is not working. Can anyone from the community tell me that, is it possible to install mongodb in Ubuntu 22.04? As , I was trying to solve this problem, I hadlooked a lot of online documentations and support where people mentioned that it is not possible to use the db with ubuntu 22.04.\nLike first some kind of impish security file Release was giving error e.g., file format is not valid and\n\u2018404: IP not found.\u2019 Then I removed that whole file as I thought it might be of different previous versions. But in the end, got other errors and a lot of complications\u2026Are there other methods?\nLike using Atlas or some kind of containerization using Dockers?As one of the other methods I tried using MongoDB Atlas and trying to connect the atlas server through VS-Code, but the connection never occurs despite of using the right connection string from the hosted server\u2026Any suggestions or help will be welcomed:)\nThanks.\nCode:"}, {"role": "assistant", "content": "Text:Atlas with Vscode should work.What error are you getting\nCheck this link\nAlso check our forum threads for alternative solutions for Mongodb on Ubuntu 20.04\nCode:"}, {"role": "user", "content": "Text:Thanks for replying.The problem is with IP address. It was not whitelisted before. I changed the setting. And now it is working.\nThanks.\nCode:"}, {"role": "assistant", "content": "Text:Hi!It will soon be a year since the stable version of ubuntu 22.04 came out and still mongo db does not support it. Please tell me if the developers plan to support mongo db for ubuntu at all? It seems that the developers of mongo db do not care about ubuntu support\nCode:"}, {"role": "assistant", "content": "Text:Related Installing mongodb over Ubuntu 22.04 - #7 by StennieThe JIRA tickets are completed so it should be possible to install following instructions in that thread.I don\u2019t know the reasons why it\u2019s not in the docs yet.I tried and replacing the last MongoDB installation commands for ubuntu 20.04 focal with with jammy installed the program.Edit: as said above, and by @chris (below) here is the link to instructions. @chaosmos.\nCode:focaljammy"}, {"role": "assistant", "content": "Text:Could you point out here exactly how i can now install mongo db on ubuntu 22.04? There are so many different options in the thread you mentioned that it is not clear which one is working and optimalAlso, could you tell me when we should expect an official release with support for ubuntu 22.04? And what is the reason for the fact that for almost a year it is impossible to install mongo db on the most popular Linux distribution in a regular way?\nCode:"}, {"role": "assistant", "content": "Text:@chaosmos please check this recent shorter discussion we had:\nHow to install mongodb 6.0 on Ubuntu 22.04 - Ops and Admin / Installation & Upgrades - MongoDB Developer Community Forums\u201cFast release cycles\u201d of operating systems favor the latest versions of libraries (ubuntu comes every 6 months). unfortunately, \u201clatest\u201d does not always mean proven to be \u201cstable\u201d or easy to migrate. Stability is important for server programs like MongoDB so they have to use battle-tested libraries (even if they may have bugs) hence the delay of support to newer OS versions.The fortunate thing is older libraries can still be installed and used mostly without any problems if all their dependencies can also be installed. you just need to dive into some settings manually. that is until developers manage to migrate to new libraries, which MongoDB also did but that is not just reflected in documents yet.\nCode:"}, {"role": "assistant", "content": "Text:Follow the existing instructions. Replace focal with jammy.Done.\nCode:focaljammy"}, {"role": "assistant", "content": "Text:Thank you. This worked perfectly for me.\nCode:"}, {"role": "assistant", "content": "Text:Hi Chris please I am completely a newbie to MongoDB but I am using ubuntu 22.04, could you help me with the clear steps to install the latest MongoDB\nCode:"}, {"role": "assistant", "content": "Text:As per @santimir:The instructions are hereStep 2: Is where focal needs to be replaced withjammy. When you copy and paste that line\nimage1113\u00d7480 73 KB\nSo that would become:\nCode:focaljammyecho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list\n"}, {"role": "assistant", "content": "Text:Just switch back to ubuntu 20.04 or some fedora or arch. Or learn and use docker instead. because this is only one package(mongoDB). God knows how many more softwares are not supported in 22.04 (They have done many critical upgrades like wayland, libssl1 \u2192 libssl3, etc. Wait a year or so for everything get supported in ubuntu 22.04 and based distros( like popos, mint, distros).\nHappy coding fella:)\nCode:"}, {"role": "assistant", "content": "Text:actually, it is not that easy (or complicated, depending on where you look at it) as you describe.you can use any version of any library (even 30 years old ones) as long as their dependencies do not contradict what the current OS uses, provided they work with the architecture.Ubuntu 22.x is called \u201cjammy\u201d and installs packages with that name. but you can still install packages from older (bionic, focal, trusty etc.) repositories if you need them. You just need to add their repository url to the apt source list file. the same also goes for independent packages like MongoDB: they have their own repository urls you need to add to apt source list.Here in this topic, installing MongoDB 6.0 on Ubuntu 22.x, we have two options:add one of older ubuntu repositories to your apt list (then follow remaining steps):wait for a new build (which is already here) and use it (@chris mentioned this many times)The first method uses MongoDB built for \u201cubuntu/focal\u201d and the second one uses \u201cubuntu/jammy\u201d build. The only thing missing is the official installation page does not yet have this on it.One can easily see which versions have been built for which ubuntu here: MongoDB Repositories. If you follow \u201cParent Directory\u201d link, you can even find builds for other Linux distros there.\nCode:echo \"deb http://security.ubuntu.com/ubuntu focal-security main\" | sudo tee /etc/apt/sources.list.d/focal-security.listecho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list"}, {"role": "assistant", "content": "Text:As you said the mongoDb server uses dependency libss1 which is upgraded to libssl3 in ubuntu 22.04. So I have to install this dependency externally which opens several velnerabilities and result in breaking system. Since there is some point in canonical\u2019s decision to depricate libssl1\n\nimage714\u00d789 52 KB\n\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to run a single node replica set? and tags: ['replication']"}, {"role": "user", "content": "Text:i want to run a singleNode replicaset in my development environment.\nShould i set voting count as 3 for my replica in this case or voting count should be default which is 1?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Divine_Cutler, the values for votes, if I\u2019m not mistaken are 0 and 1.In the case of a single node replica set, since there is only a single node the vote count would need to be set at 1. Changing the vote count, even if it could be greater than 1, wouldn\u2019t have any impact as it\u2019s the only node that can vote. If the machine is running it\u2019s automatically the primary node. If it\u2019s down, well then it doesn\u2019t matter how many votes it gets. While a single node replica set might be fine for development purposes, it is strongly cautioned against putting that into production.What are you trying to accomplish with having a single node replica set?\nCode:"}, {"role": "user", "content": "Text:@Doug_Duncan for testing changeEvents in mongodb\nCode:"}, {"role": "assistant", "content": "Text:Hi @Divine_Cutler, you can follow this documentation to convert your stand alone to a single node replica set.\nCode:"}, {"role": "assistant", "content": "Text:If you going to create a repl set to test think you need atlest two members to witness replication and voting would only matter if there is more than one member.Else single node I dont think would be much different from a single mongod instance.\nCode:"}, {"role": "assistant", "content": "Text:@Kirk-PatrickBrown For what @Divine_Cutler is doing(change streams) using a replicaset of one is perfectly fine.But for a production system where you want some kind of HA, yes you need three nodes. PSA or PSS.\nCode:"}, {"role": "user", "content": "Text:@chris @Doug_Duncan yes, but i do have a doubt when comparing a singleNodeReplicaset with a 3node-replicaset.When i run a 3node replicaset node1,node2,node3 and if node1 goes down, then among node2,node3 a primary node is elected.\nScreenshot 2020-05-23 at 05.28.121124\u00d7352 36.3 KBWhen node2 goes down, then node3 remains as secondary.\nScreenshot 2020-05-23 at 05.34.33900\u00d7334 32.8 KBis it possible to have the node3 as a primaryNode when node1,node2 is down? if it is not possible, then i would like to know the reason on how is it possible for a singleNodeReplica set to act as a primaryNode.\nCode:"}, {"role": "assistant", "content": "Text:@Divine_Cutler when you need to have a majority of the nodes up for a replica set to have a primary. This means in a three node replica set that two members must be available.Check out the Consider Fault Tolerance section of the Replica Set Architectures document.Having a single node running from a three node replica set is not the same as running a single node replica set.\nCode:"}, {"role": "user", "content": "Text:@Doug_Duncan thank you. i understand this post. but here is my doubt.Let\u2019s say that i have a singleNodeReplicaSet - it accepts both read/write. then i add 2 additionalnodes to this singleNodeReplicaSet which becomes a 3NodeReplicaSet.So, Once a singleNodeReplicaSet that runs on its own is converted to 3NodeReplicaSet, i could never scaledown the 3NodeReplicaSet back to a singleNodeReplicaSet and make this singleNodeReplicaSet to accept read/write requests?\nCode:"}, {"role": "assistant", "content": "Text:@Divine_Cutler, you can force reconfigure your remaining member to remove the downed nodes, but that\u2019s not recommended unless absolutely necessary.If you\u2019re running a three node replica set and two nodes go down I would first look into why I have two nodes down at the same time. While bad things can, and do, happen, it\u2019s rare in my experience for two of the three nodes in a replica set to go down at the same time. Your time is better spent trying to bring the downed nodes back online. If you can get just one of them up and running you have a majority again and one will be promoted to PRIMARY status.Forcing your three node replica set back down to a single node replica set is very dangerous, especially in a production environment as you\u2019ve lost any sort of HA. I would strongly caution against doing that.\nCode:"}, {"role": "user", "content": "Text:@Doug_Duncan thank you.i have one more question and it troubles me a little bit.Please assume this scenario.i have a 3nodeReplicaSet (node1,node2,node3). There are no problems in the configuration, so everything is functioning as expected.Assume, there are huge number number of write/update/delete operations going on.Then, at one point, the oplog collection in primaryNode(node1) reached the memory limit and as it is a capped collection, the old data in oplog collection gets overridden and the data from oplog gets synced successfully to the secondaryNodes(node2,node3) without any problems.Suddenly Node3 goes down for some reason(may be the developer shut it down), but the application is functioning successfully as node1,node2 are running fine. But still there are huge number of write/update/delete ongoing.My understanding of data sync between nodes in replicaSet is, the secondaryNodes replicate the data from primaryNode by reading the oplog collection of the primaryNode.Coming back to our scenario,\nAssume, that the oplog got filled completely thrice counting from the moment node3 was down till the moment node3 was started again. Now, if the node3 was started again, then\nCode:"}, {"role": "user", "content": "Text:@Doug_Duncan i got answer for my above question.even though i went throught that article previously, i forgot about it yesterday\nCode:"}, {"role": "assistant", "content": "Text:Hi,\nWhat is this tool name ?\nCode:"}, {"role": "assistant", "content": "Text:While a single node replica set might be fine for development purposes, it is strongly cautioned against putting that into production.Can you please expand on why this is the case when all 3 nodes would be running on a single VPS anyway? What is the failure case that a single node replica does not catch that a 3-node replica does catch - when the context is a single physical server that regularly does a mongodump?Thank you.\nCode:"}, {"role": "assistant", "content": "Text:Can you please expand on why this is the case when all 3 nodes would be running on a single VPS anyway?Running all the nodes of a replica set on the same piece of hardware is really not the best because you have a single point of failure.An upgrade is one scenario that multi-node replica set, even on single hardware, is something that can be done without down time. With a single node replica set you cannot.\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m curious if @Doug_Duncan concurs\u2026\nThis doesn\u2019t really answer the question; I realize that the hardware is a single point of failure running with and without replicas (if they\u2019re all contained on the same hardware). The question is: how or why is a single node replica more dangerous than mongodb running without replicas?If we only want to scale vertically in production, then why isn\u2019t a single node replica usable in production (considering the same careful backup process we use with our single node non-replica mongodb)? The point is to be able to use transactions.\nCode:"}, {"role": "assistant", "content": "Text:The question is: how or why is a single node replica more dangerous than mongodb running without replicas?This is not the same question and it is not what was said. What was said was that running a single node replica set was risky.A single node replica set IS NOT MORE dangerous than an instance without replication. They represents the SAME HIGH risk of losing data. Replication is needed for both transactions and change streams.\nCode:"}, {"role": "assistant", "content": "Text:Sorry for the lack of clarity on the question.If that is true, then why is it officially OK to run mongodb in production without replicas and running a single node replica in production is listed as only for development environments / testing (everywhere I\u2019ve seen it talked about so far)? Surely, then, it is a reasonable workaround in production for the transaction support issue?\nThanks again for entertaining my inquieries.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Query on non empty object field having multiple keys or to check size of object greater than 1 and tags: ['queries', 'schema-validation']"}, {"role": "user", "content": "Text:We have one use case. Let\u2019s suppose I have two documents as given below.Now I want those result whose \u201ctest\u201d field has property other than \u201ca\u201d or in another way, I want those objects which have multiple keys/properties in a \u201ctest\u201d field or to check the size of an object greater than 1So, the result will be:I tried to make a query for the above output as shown below and it working as expecteddb.col.find({\"test\": {\"$gt\": {\"a\": 1} }})So, is that the right thing to do? Any downside of doing it? We want to lever-age indexes as well considering that we have indexes on \u2018test\u2019 fieldPlease let me know your inputs on this.Thanks.\nCode:{\n \"_id\": ObjectID('123'),\n \"test\": {\n \"a\":1,\n \"b\":1\n }\n},\n{\n \"_id\": ObjectID('456'),\n \"test\": {\n \"a\":1\n }\n{\n \"_id\": ObjectID('123'),\n \"test\": {\n \"a\":1,\n \"b\":1\n }\n}\ndb.col.find({\"test\": {\"$gt\": {\"a\": 1} }})"}, {"role": "assistant", "content": "Text:Hello @Aamod_Pisat, welcome to the MongoDB Community forum!You can use the $exists query operator to check if a field exists or not - within a document. For example, the querydb.col.find( { ''test.a': { $exists: true } )returns both the documents from your example collection.db.col.find( { ''test.b': { $exists: true } )returns only one document, the one with \"_id\": ObjectID('123').\nCode:db.col.find( { ''test.a': { $exists: true } )db.col.find( { ''test.b': { $exists: true } )\"_id\": ObjectID('123')"}, {"role": "user", "content": "Text:Hi @Prasad_Saya, Thanks for your response. But I am not expecting that. $exists will return if the key is present or not. What I want is I would like to get that any other exists than given key in object field or I want is if that object has multiple keys or not i.e size of object length should be greater than 1.\nSo, for that, we used $gt operator. So, is that the right thing to do, Any downside of doing as we want to leverage indexes as well?\nCode:$gt"}, {"role": "assistant", "content": "Text:What I want is I would like to get that any other exists than given key in object field or I want is if that object has multiple keys or not i.e size of object length should be greater than 1.\nSo, for that, we used $gt operator. So, is that the right thing to doThat is not the right query for it.You have to write an aggregation query and use the $objectToArray aggregation operator to convert the object as an array and then find the length of the array. If the length of the array is greater than 1, then there are more than one field in the object. See the example from the documentation explains how to convert the object to an array.\nCode:$gt"}, {"role": "user", "content": "Text:Okay thanks, @prasad. Using above, if I have index on \u2018test\u2019 field. So, will it leverage that or will this have any performance impact on querying documents\nCode:"}, {"role": "assistant", "content": "Text:@Aamod_Pisat, I am not sure about that (I think it will not use the index). You can check if a query is using an index or not by using the explain on the query. The explain method generates a query plan which will have information about index usage by the query.\nCode:"}, {"role": "user", "content": "Text:HI @Prasad_Saya, We tried working with aggregation query using $objectToArray but the query doesn\u2019t use indexes as it\u2019s taking COLSCAN even though I have an index on that field.\nBut below query which I shared is taking index i.e. IXSCAN. So, hopefully, there won\u2019t be any downside to doing this.db.col.find({\"test\": {\"$gt\": {\"a\": 1} }})Let us know your thoughts on this.Thanks.\nCode:$objectToArraydb.col.find({\"test\": {\"$gt\": {\"a\": 1} }})"}, {"role": "assistant", "content": "Text:Hello @Aamod_Pisat, as I had mentioned earlier, you cannot use that query to count the number of fields in the test object (or sub-document ). The query you had posted doesn\u2019t the number of fields - it only finds documents where the \"test.a\" value is greater than 1.Yes, the index defined on the \"test.a\" will be used in the query - as you had mentioned there is an IXSCAN from the query plan.Please note that the two queries have different purposes.\nCode:test\"test.a\"1\"test.a\""}, {"role": "assistant", "content": "Text:Hello @Aamod_Pisat, and welcome to the community,\nyou can use $jsonSchema as an alternative to @Prasad_Saya 's solution;\nCode:db.collection.find({$nor:[{\n \"$jsonSchema\":{\n \"properties\":{\n \"test\":{\n \"type\":\"object\",\n\t \"properties\":{\"a\":{}},\n\t \"additionalProperties\": false\n }\n }\n }\n}]})"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: What is the best schema for a blog post for storing the blog content, like, share and comment? and tags: ['data-modeling']"}, {"role": "user", "content": "Text:I am building an API backend for a social media platform where users can post blogs and other user can like, share and comment on it.Along with the basic details of the blog post (title, image, author name and photo), the API should returnI would like to know the best schema design for this requirement. I am planning to store blog content, like and comment in one collection. Please suggest\nCode:"}, {"role": "assistant", "content": "Text:Hi @Ummer_Irshad ,Schema design may vary between different requirements and application data access.The main guidance is that data that is queried together should be stored together in a document while not hitting any known antipattern.With the example you describe here and the limited information it sounds like you can use the following schema (extended reference pattern):Blogs collectionComments collectionLikes collection :Let me know if that makes sense.Read the following:Have you ever wondered, \"How do I model a MongoDB database schema for my application?\" This post answers all your questions!Get a summary of the six MongoDB Schema Design Anti-Patterns. Plus, learn how MongoDB Atlas can help you spot the anti-patterns in your databases.Thanks\nPavel\nCode:{\n_id : ...\nTitle : ...\nPostTime : ... \nnLikes : ...\nNumComments : ...,\nAuthor : { \n UserId : ...,\n ProfilePic : ..., \n Name : ....\n}\n...\n}\n{\n _id : ...,\n BlogId : ... // Reference to blogs\n PostTime : ... ,\n Text : ... \n Author : { \n UserId : ...,\n ProfilePic : ..., \n Name : ....\n}\n,\nnLikes : ...\n}\n{\n _id : ...,\n ReferenceId : ... // Reference to blogs or comments\n LikeTime : ... ,\n Author : { \n UserId : ...,\n ProfilePic : ..., \n Name : ....\n}\n"}, {"role": "user", "content": "Text:Thanks Pavel for your quick response.One drawback I could see here is about embedding Author info inside collection. So, as and when a user updates the profile pic, we have to update it in all of his blogs, comments and likes? Is there any way to handle this?What about the below schema? Here, we are storing blog and comments in a single collection, with a field \u201ctype\u201d to distinguish it. If it is a comment, then we will keep the blogId in it\u2019s \u201cparent_id\u201d field. Then, we need to have separate collection for \u201cUsers\u201d. And, of course, we need to run a second query to get the profile pic.Any suggestions?\nCode:{\n\tid: { type: String, },\n\ttype: { type: String, required: true, enum: ['post', 'comment'] },\n\tpost_uid: { type: String, required: true },\n\tcontent: { type: String, required: false },\n\tauthor_id: { type: Number, required: true },\n\ttimestamp: { type: Date, required: true },\n\tvote_count: { type: Number, required: true },\n\tcomment_count: { type: Number, required: true },\n\tparent_id: { type: String, required: false },\n\tvotes: [\n\t\t{\n\t\t\tvote_id: { type: String},\n\t\t\tvoted_user_id: { type: Number, required: true },\n\t\t\ttimestamp: { type: String, required: true },\n\t\t},\n\t],\n})\n"}, {"role": "assistant", "content": "Text:Hi @Ummer_Irshad ,Well having the documents in a single collection or 2 seperate collections is not that impacting as long as you will need the same amount of reads/queries to fetch it.You can potentially store just pointers to the profile pic of each user in the users collection.However, another idea is to keep the most updated profile pic in a users generic name and to overwrite this picture name with the new one each time. This way you will not need to have the updates. And you will get history of pictures as well .Regarding the votes (likes) in an array just note that there is a possible unbound arrays there if this grows to thousands or more in a post or comment that is highly popular \u2026 Consider if that is ok to go that path or you need outlier pattern\u2026Thanks\nPavel\nCode:https://hosting.com/user_123456/profile_current.jpg\n"}, {"role": "assistant", "content": "Text:@Pavel_Duchovny\ni think he means embedding Author in the document (that exists in the Blogs collection)\nso what about this situation ?\nif an Author\u2019s name for example change, we have then to query all the blogs of that author and update them\nis there a better way of doing this ??\ncould you explain further this idea : You can potentially store just pointers to the profile pic of each user in the users collection.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Khammassi_HoussemEdd ,How many scenarios do change previous posts auther name? Does it make sense for applications?In case you still want to follow this scenario you can have several options:The idea is to avoid any kind of lookup for user details for a generic posts view.Ty\nCode:"}, {"role": "assistant", "content": "Text:you can use populate() of mongoose.\nUsing this we just have to provide reference of the author in the blogs.\nyou can read more about it here mongoose populate\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m not a specialist in this domain; however, I think you should get in touch with content creators with a large fanbase that can help you with your problem. Social media platforms are used for various purposes, from entertainment to business, and if you want to become famous, you should post quality content.\nCode:"}, {"role": "assistant", "content": "Text:It\u2019s been a hot minute since this thread was active. Anyway, here\u2019s my two cents: I\u2019d recommend splitting your data into separate collections - one for \u2018Posts\u2019, another for \u2018Comments\u2019, and finally \u2018Likes\u2019. This would make your model more flexible and efficient.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to limit the number of document updates? and tags: ['crud']"}, {"role": "user", "content": "Text:Hi\nI want to limit the number of document updates in one command.for examplehttps://jira.mongodb.org/browse/SERVER-55967\nCode:db.users.updateMany(\n ,\n ,\n {\n limit : 100\n }\n);\n"}, {"role": "assistant", "content": "Text:Check this link.\nCode:"}, {"role": "user", "content": "Text:Thanks Ramachandra_Tummala.\nThis is not my answer but this post is near.\nactually , i want update only 100 document in one command in php app.Like Limit clause in MariaDBFor example:\ni have 7 documents in tmp collection and have 3 server that want connect to the MongoDB server for run that command(one update command).In a hypothesis concurrency (limit of update is 3):\nCode:tmp{\n \"_id\" : 1,\n \"name\" : \"A\",\n},\n{\n \"_id\" : 2,\n \"name\" : \"B\",\n},\n{\n \"_id\" : 3,\n \"name\" : \"C\",\n},\n{\n \"_id\" : 4,\n \"name\" : \"D\",\n},\n{\n \"_id\" : 5,\n \"name\" : \"E\",\n},\n{\n \"_id\" : 6,\n \"name\" : \"F\",\n},\n{\n \"_id\" : 7,\n \"name\" : \"G\",\n}\n3 Time ****************************** [id of docs modified]\n |SV1 -----[Update CMD]------------> 1,2,4\n Requests|SV2 ----------[Update CMD]-------> 5\n |SV3 -------[Update CMD]----------> 3,6,7\n"}, {"role": "user", "content": "Text:Do you have not any other solution?\nCode:"}, {"role": "user", "content": "Text:Please vote \u2026 Hi\nI want to limit the number of document updates in one command.\n\nfor example\n\ndb.users.updateMany(\n ,\n ,\n {\n limit : 100\n }\n);\n\n\nhttps://www.mongodb.com/community/forums/t/how-to-limit-the-number-of-document-updates/102204/3\nCode:"}, {"role": "assistant", "content": "Text:These code doesn\u2019t works\nUpdate many doesn\u2019t work wit limit\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Cannot connect to replica set via mongo compass and tags: ['replication', 'compass', 'mongodb-shell']"}, {"role": "user", "content": "Text:I have a mongodb cluster on 3 different VMs. When I try to access to the replicaset via compass using this GUI :mongodb://at192.168.20.1:27017,192.168.20.2:27017,192.168.20.3:27017/?replicaSet=rs0&authSource=admin&appName=mongosh+1.4.1It says getaddrinfo ENOTFOUND masternode or sometimes it says getaddrinfo ENOTFOUND client1However, if I try to connect separately to each one using :\nmongodb://at192.168.20.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.4.1&authMechanism=DEFAULT\n\nmongodb://at192.168.20.3:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.4.1&authMechanism=DEFAULT\nIt works just fine.Is there anything wrong with my replicaset GUI and how can I fix this?\nFYI, 192.168.20.1, 192.168.20.2 and 192.168.20.3 is associated with masternode, client1 and client2 respectively as well as I use at instead of @ due to new user tag thingy\nYour reply is very appreciated.\nCode:"}, {"role": "assistant", "content": "Text:I think your appNsme should be Compass\nWhy it is showing mongosh\nCode:"}, {"role": "user", "content": "Text:I tried it and the outcome is the same as I mentioned in the post that I\u2019m able to access to separate mongodb but if I try to access to the whole replica set it shows the same error.\nCode:"}, {"role": "assistant", "content": "Text:ENOTFOUNDis related to DNS information missing. The following is certainly wrong:at192.168.20.1:27017\nCode:"}, {"role": "user", "content": "Text:Hello,\nI missed type the dns. The actual dns that I used was mongodb://@192.168.20.1:27017,192.168.20.2:27017,192.168.20.3:27017/?replicaSet=rs0&authSource=admin&appName=mongosh+1.4.1 for replica setmongodb://@192.168.20.X:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.4.1&authMechanism=DEFAULT for separate connection.\nCode:"}, {"role": "user", "content": "Text:Before @ user:password\nCode:"}, {"role": "assistant", "content": "Text:Post a screenshot that shows exactly what you are doing that shows the error you are having.Also post a screenshot that shows using the mongosh with the same connection.Please do not redact or obfuscate the user name and password you use since the redaction might hide the error you make. If you are afraid to share the password for a server running on a private network you may always create a dummy user that only has read access on a dummy database.\nCode:"}, {"role": "user", "content": "Text:The first one is the one that I cannot access and error is as follows\n\nimage928\u00d7566 36.4 KB\nThis one it works just fine\n\nimage938\u00d7473 29.8 KB\n\n\nimage1866\u00d7882 44.5 KB\n\nCode:"}, {"role": "assistant", "content": "Text:I think you have an issue with your replica set configuration.I suspect that your replica set configuration uses host names rather than the IP addresses you use to connect, and that some of those are not resolved correctly by your DNS.Using a command line terminal share the output of the following.Then connect with mongosh to a single node, 192.168.20.1:27017 for example and share the output of the command:\nCode:ping masternode\nrs.status()\n"}, {"role": "user", "content": "Text:Here is the result of rs.status()\n\nimage1266\u00d7522 31.7 KB\nThis is the result of ping masternode\n\nimage1023\u00d7446 11.4 KB\n\nCode:"}, {"role": "assistant", "content": "Text:If this a replica set it should show all 3 members info but showing as standalone\nHave you run rs.initiate() and added other 2 nodes?\nPlease show rs.conf() output\nCode:"}, {"role": "user", "content": "Text:{\nset: \u2018rs0\u2019,\ndate: ISODate(\u201c2022-05-30T07:31:56.942Z\u201d),\nmyState: 1,\nterm: Long(\u201c47\u201d),\nsyncSourceHost: \u2018\u2019,\nsyncSourceId: -1,\nheartbeatIntervalMillis: Long(\u201c2000\u201d),\nmajorityVoteCount: 2,\nwriteMajorityCount: 2,\nvotingMembersCount: 3,\nwritableVotingMembersCount: 3,\noptimes: {\nlastCommittedOpTime: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\nlastCommittedWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nreadConcernMajorityOpTime: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\nappliedOpTime: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\ndurableOpTime: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\nlastAppliedWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nlastDurableWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d)\n},\nlastStableRecoveryTimestamp: Timestamp({ t: 1653895860, i: 1 }),\nelectionCandidateMetrics: {\nlastElectionReason: \u2018stepUpRequestSkipDryRun\u2019,\nlastElectionDate: ISODate(\u201c2022-05-25T02:51:46.241Z\u201d),\nelectionTerm: Long(\u201c47\u201d),\nlastCommittedOpTimeAtElection: { ts: Timestamp({ t: 1653447105, i: 1 }), t: Long(\u201c46\u201d) },\nlastSeenOpTimeAtElection: { ts: Timestamp({ t: 1653447105, i: 1 }), t: Long(\u201c46\u201d) },\nnumVotesNeeded: 2,\npriorityAtElection: 1,\nelectionTimeoutMillis: Long(\u201c10000\u201d),\npriorPrimaryMemberId: 1,\nnumCatchUpOps: Long(\u201c0\u201d),\nnewTermStartDate: ISODate(\u201c2022-05-25T02:51:46.260Z\u201d),\nwMajorityWriteAvailabilityDate: ISODate(\u201c2022-05-25T02:51:47.302Z\u201d)\n},\nmembers: [\n{\n_id: 0,\nname: \u2018masternode:27017\u2019,\nhealth: 1,\nstate: 1,\nstateStr: \u2018PRIMARY\u2019,\nuptime: 607291,\noptime: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\noptimeDate: ISODate(\u201c2022-05-30T07:31:48.000Z\u201d),\nlastAppliedWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nlastDurableWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nsyncSourceHost: \u2018\u2019,\nsyncSourceId: -1,\ninfoMessage: \u2018\u2019,\nelectionTime: Timestamp({ t: 1653447106, i: 1 }),\nelectionDate: ISODate(\u201c2022-05-25T02:51:46.000Z\u201d),\nconfigVersion: 1,\nconfigTerm: 47,\nself: true,\nlastHeartbeatMessage: \u2018\u2019\n},\n{\n_id: 1,\nname: \u2018client1:27017\u2019,\nhealth: 1,\nstate: 2,\nstateStr: \u2018SECONDARY\u2019,\nuptime: 448792,\noptime: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\noptimeDurable: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\noptimeDate: ISODate(\u201c2022-05-30T07:31:48.000Z\u201d),\noptimeDurableDate: ISODate(\u201c2022-05-30T07:31:48.000Z\u201d),\nlastAppliedWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nlastDurableWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nlastHeartbeat: ISODate(\u201c2022-05-30T07:31:55.333Z\u201d),\nlastHeartbeatRecv: ISODate(\u201c2022-05-30T07:31:55.333Z\u201d),\npingMs: Long(\u201c0\u201d),\nlastHeartbeatMessage: \u2018\u2019,\nsyncSourceHost: \u2018masternode:27017\u2019,\nsyncSourceId: 0,\ninfoMessage: \u2018\u2019,\nconfigVersion: 1,\nconfigTerm: 47\n},\n{\n_id: 2,\nname: \u2018client2:27017\u2019,\nhealth: 1,\nstate: 2,\nstateStr: \u2018SECONDARY\u2019,\nuptime: 607285,\noptime: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\noptimeDurable: { ts: Timestamp({ t: 1653895908, i: 1 }), t: Long(\u201c47\u201d) },\noptimeDate: ISODate(\u201c2022-05-30T07:31:48.000Z\u201d),\noptimeDurableDate: ISODate(\u201c2022-05-30T07:31:48.000Z\u201d),\nlastAppliedWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nlastDurableWallTime: ISODate(\u201c2022-05-30T07:31:48.203Z\u201d),\nlastHeartbeat: ISODate(\u201c2022-05-30T07:31:55.295Z\u201d),\nlastHeartbeatRecv: ISODate(\u201c2022-05-30T07:31:54.984Z\u201d),\npingMs: Long(\u201c0\u201d),\nlastHeartbeatMessage: \u2018\u2019,\nsyncSourceHost: \u2018masternode:27017\u2019,\nsyncSourceId: 0,\ninfoMessage: \u2018\u2019,\nconfigVersion: 1,\nconfigTerm: 47\n}\n],\nok: 1,\n\u2018$clusterTime\u2019: {\nclusterTime: Timestamp({ t: 1653895908, i: 1 }),\nsignature: {\nhash: Binary(Buffer.from(\u201cca77f671a7f355a16649c47ff0d4f500f38d0e0a\u201d, \u201chex\u201d), 0),\nkeyId: Long(\u201c7097159497856057348\u201d)\n}\n},\noperationTime: Timestamp({ t: 1653895908, i: 1 })\n}Here is my rs.status()\nCode:"}, {"role": "user", "content": "Text:{\n_id: \u2018rs0\u2019,\nversion: 1,\nterm: 47,\nmembers: [\n{\n_id: 0,\nhost: \u2018masternode:27017\u2019,\narbiterOnly: false,\nbuildIndexes: true,\nhidden: false,\npriority: 1,\ntags: {},\nsecondaryDelaySecs: Long(\u201c0\u201d),\nvotes: 1\n},\n{\n_id: 1,\nhost: \u2018client1:27017\u2019,\narbiterOnly: false,\nbuildIndexes: true,\nhidden: false,\npriority: 1,\ntags: {},\nsecondaryDelaySecs: Long(\u201c0\u201d),\nvotes: 1\n},\n{\n_id: 2,\nhost: \u2018client2:27017\u2019,\narbiterOnly: false,\nbuildIndexes: true,\nhidden: false,\npriority: 1,\ntags: {},\nsecondaryDelaySecs: Long(\u201c0\u201d),\nvotes: 1\n}\n],\nprotocolVersion: Long(\u201c1\u201d),\nwriteConcernMajorityJournalDefault: true,\nsettings: {\nchainingAllowed: true,\nheartbeatIntervalMillis: 2000,\nheartbeatTimeoutSecs: 10,\nelectionTimeoutMillis: 10000,\ncatchUpTimeoutMillis: -1,\ncatchUpTakeoverDelayMillis: 30000,\ngetLastErrorModes: {},\ngetLastErrorDefaults: { w: 1, wtimeout: 0 },\nreplicaSetId: ObjectId(\u201c627e2cebd23c7aae01154b0b\u201d)\n}\n}>\nThis is rs.config()\nCode:"}, {"role": "assistant", "content": "Text:Can you connect by hostname instead IP?\nAre other 2 nodes pingable and resolving to the ips you are using\nAlso output of cat /etc/hosts\nCode:"}, {"role": "user", "content": "Text:Here is the cat of /etc/hosts\n\nimage692\u00d7400 19.8 KB\nI had tried using the hostname instead of IPs and it resulted in the same error.Yes, every node can ping to each other using ping hostname and the ip is all correct.\nCode:"}, {"role": "assistant", "content": "Text:Looks ok\nDid you try to connect to your replica set using hostnames in your connect string?\nCode:"}, {"role": "user", "content": "Text:Yes I did. It gives me the same error\n\nimage915\u00d7835 57.5 KB\n\nCode:"}, {"role": "assistant", "content": "Text:ENOTFOUND means that the host name masternode cannot be found.In one of your previous post, you shown that you can ping masternode and the other 2 hosts of your replica set.The only conclusion I can think of, is that you are not running Compass from the same machine as the one you used to run the ping commands.The host names of your replica set must be DNS resolvable from all machines you are using to access the replica set. They should all resolve to IP addresses that are routed from all machines you are using to access the replica set.\nCode:"}, {"role": "user", "content": "Text:That might be the case because I run the replicaset on 3 separate VMs. Are there any ways for me to allow compass on my pc to be able to access to the set? I tried using ufw allow from 0.0.0.0/0 on every single VM but it still doesn\u2019t work\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Password contains unescaped characters and tags: ['node-js']"}, {"role": "user", "content": "Text:MongoParseError: Password contains unescaped characters\nat new ConnectionString (C:\\Users\\HEWLETT-PACKARD\\Desktop\\flutter\\tysBackend\\node_modules\\mongodb-connection-string-url\\lib\\index.js:90:19)\nCode:"}, {"role": "assistant", "content": "Text:Try try encoding the password text with something like:\nCode:const adminPassword = encodeURIComponent( process.env.ADMIN_PASSWORD )\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Path Collision trying to Export Collection and tags: ['compass']"}, {"role": "user", "content": "Text:I\u2019m completely new to Mongo so please bear with me. I\u2019m using Compass and I\u2019m able to view collections, query the data, etc. Everything is working fine.When I try to export a whole collection, on most collections, it works fine.When I tried to export 1 collection (all fields) to a CSV file, I get an error:Path collision at Contact.Email remaining portion EmailI\u2019m not selecting individual fields, or doing anything crazy. I\u2019m just trying to export the whole collection.I noticed that when I view the documents in the collection, I don\u2019t even see the offending fields.\n\nScreen Shot 2021-07-20 at 9.46.52 PM1520\u00d7602 64.5 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Path collision atWhat is your Compass version?\nCould be bug with latest version\nCheck this linkhttps://jira.mongodb.org/browse/COMPASS-4723?jql=project%20%3D%20COMPASS%20AND%20fixVersion%20%3D%201.24.1\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m having the same issues and I\u2019m running the most recent Compass version.\nCode:"}, {"role": "assistant", "content": "Text:Did you try with lower version of Compass?or try the fix given in that link-unselect the fields causing the error\nCode:"}, {"role": "assistant", "content": "Text:Hi,I am facing the same issue while exporting a particular collection from compass version 1.30.1, I tired to omit the offending column, it stuck at next column.\nHowever, I am able to export other collections.Hope you can suggest a solution.Thank you.\nSiva\nCode:"}, {"role": "assistant", "content": "Text:Did you try with mongoexport from command line?\nor use a lower version of Compass\nShow the sample doc\nHow many records in this collection?\nCode:"}, {"role": "assistant", "content": "Text:Hi Ram,Thanks for the response.No, I did not try the command line option for export, I will try.If compass version is the issue, I was able to export another document \u201cGrades\u201d.The document that I am trying to export is \u201ccompanies\u201d under sample_training, it is having 9.500 records and of size 15.9MB.The document and fields are too long to give here.Cheers\nSiva\nCode:"}, {"role": "assistant", "content": "Text:I\u2019ve got the same issue.\nMy solution is:It\u2019s strange that some object-type is ok but some has issue\u2026 I\u2019m not sure why\nCode:"}, {"role": "assistant", "content": "Text:Also, encounter the same issue, the issue is the field showing the error is not consistent in the collection, uncheck the field showing that error and export, Don\u2019t know how it works but it will still export the field if it is available.\nCode:"}, {"role": "assistant", "content": "Text:Thanks, Your solution helped for my testing purposes.\nI received the same error and I unselected the reviews_scores (along with all its fields.)\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997) and tags: ['queries']"}, {"role": "user", "content": "Text:I\u2019m new with mongodb. I\u2019ve tried to add new entry and get this error.[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)\nCode:"}, {"role": "assistant", "content": "Text:Are you getting this Compass or mongosh or in a program?\nIf your installation has a self-signed certificate, you have to tell MongoDB tooling where to get a copy of the acceptable certificate.\nE.g., in PHP, you\u2019d connect something like\nnew MongoDB\\Client($mongodb_uri, b['tls' => true, 'tlsCAFile' => $mongodb_cert_path]);\nCode:new MongoDB\\Client($mongodb_uri, b['tls' => true, 'tlsCAFile' => $mongodb_cert_path]);"}, {"role": "assistant", "content": "Text:I saw an answer that worked for me, it appears i had not yet installed the python certificates on my mac, so from the following path i went and installed itOnly change the version of your python, after that everything, worked fine for mePS: I had been trying to solve the problem for half a day, I even asked ChatGPT\nCode:/Applications/Python 3.10/Install Certificates.command\n"}, {"role": "user", "content": "Text:Unfortunately that didn\u2019t help\nCode:"}, {"role": "user", "content": "Text:Using pyCharm, macOs Ventura 13.1Full code:\nCode:from pymongo import MongoClient\ncluster = MongoClient('mongodb+srv://pystudy:@cluster0.fyglnvy.mongodb.net/?retryWrites=true&w=majority')\ndb = cluster['test']\ncollection = db['test']\n\npost = {'_id': 0, 'name': 'Jeff', 'score': 9}\ncollection.insert_one(post)\n"}, {"role": "assistant", "content": "Text:open a new terminal and follow these (use \u201cpython\u201d and \u201cpip\u201d if \u201cpython3\u201d and \u201cpip3\u201d does not work):Package Versiondnspython 2.3.0\npip 22.2.2\npymongo 4.3.3\nsetuptools 63.2.0if your code works this way, then the installation pycharm uses might be broken and need a repair or full reinstllation. (or pycharm is broken)if not, then either your system has a problem or you messed with some settings in Atlas (I can\u2019t point any).\nCode:mkdir test && cd testpython3 -m venv .venv.venv/Scripts/activatepip3 install pymongopip3 listpython3"}, {"role": "assistant", "content": "Text:This worked for me.\nThank you mate!\nCode:"}, {"role": "assistant", "content": "Text:I had similar problems and it felt like I tried everything. MacOS Ventura 13.2.1, PyCharm 2022.3.3 Professional, Python 3.11.2The final fix\u2026I rebooted!!!So, some of these changes don\u2019t take effect until a complete reboot.\nCode:"}, {"role": "assistant", "content": "Text:For me - After a few hours I found this thread that said that I need to open the client using certifiAble to use Compass with no problems, Atlas UI all looks good but couldn\u2019t connect using Python.Using Python 3.11, pymongo==3.11, Mac Monterey, VS CodeAs a newbie I am disappointed that I had to spend a lot of time on ChatGPT and Google to resolve this.\nNot a fantastic first impression but happy to blame myself for something i missed - maybe others will miss whatever I missed too\u2026\nCode:"}, {"role": "assistant", "content": "Text:Thank you mate!This worked for me.\nCode:"}, {"role": "assistant", "content": "Text:I had similar problems and it felt like I tried everything...\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Duplicate Data Issue and tags: ['time-series']"}, {"role": "user", "content": "Text:Hello everyone,I\u2019ve been using influxdb for time series for the last past year but I wanted to try mongo time series recently. and I\u2019ve been doing some tests however I couldnt find out why it allows duplicate values and a way to prevent it. Basically I\u2019m writing data in bulk every few minutes and usually 1 minute of data is duplicate in the batch. with the same metadata and everything. I expect mongodb to skip these duplicate values. How can I achive this without creating an _id field out of metadataThanks\nCode:"}, {"role": "user", "content": "Text:oh man, I just noticed even generating _id out of metadata on the application side doesn\u2019t work. It allows duplicate _id fields. I hope there is a fix for this issue.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Gorkem_ErdoganIf you\u2019re using MongoDB 5.0.0, 5.0.1, or 5.0.2, please upgrade to the latest version (5.0.4 currently). The same applies if you\u2019re using the 4.4 series. Latest is 4.4.10 in the 4.4 series.There was an issue that was detected in early versions of the 5.0 series that allows duplicate unique index entries (see SERVER-58936).Best regards\nKevin\nCode:"}, {"role": "user", "content": "Text:Hello,I use serverless mongodb version 5.1.0\nCode:"}, {"role": "assistant", "content": "Text:Hi @Gorkem_ErdoganThat is interesting. The duplicate _id should be fixed in 5.1.0. Do you mind providing more information about this?Best regards\nKevin\nCode:"}, {"role": "user", "content": "Text:Hello,Well it is nothing really special. I\u2019ve been testing it on a jupyter notebook using pymongo Version: 4.0At first, I let mongodb to handle _id field thinking it could handle duplicate data with the same metadata and timestamp. and I think this is really important for a timeseries database. It should not let insert if the metadata and the timestamp are the same. we shouldnt be dealing with generating _id field for this purpose\u2026using insertMany, inserted couple of hundred documents. Below is one of the documents;then noticed it does not handle duplicate data so I decided to generate _id field on my application side. _id generated using metadata field and timestamp as below;but still, duplicates were allowed\u2026 here is a screenshot\nScreenshot 2021-12-02 144234747\u00d7716 27.6 KB\n\nCode:{\n \"timestamp\": {\n \"$date\": \"2021-12-01T18:58:00.000Z\"\n },\n \"metadata\": {\n \"chart\": \"candles\",\n \"interval\": \"1min\",\n \"market\": \"USD\",\n \"symbol\": \"REQ\"\n },\n \"open\": 0.7027,\n \"low\": 0.7015,\n \"high\": 0.7083,\n \"close\": 0.7074,\n \"volume\": 163137\n}\n{\n \"timestamp\": {\n \"$date\": \"2021-12-01T18:58:00.000Z\"\n },\n \"metadata\": {\n \"chart\": \"candles\",\n \"interval\": \"1min\",\n \"market\": \"USD\",\n \"symbol\": \"REQ\"\n },\n \"open\": 0.7027,\n \"_id\": \"REQ-USD-1min-candles-1638385080\",\n \"low\": 0.7015,\n \"high\": 0.7083,\n \"close\": 0.7074,\n \"volume\": 163137\n}\n"}, {"role": "assistant", "content": "Text:Hi @Gorkem_ErdoganA timeseries collection is quite different from a normal MongoDB collection. This is because although superficially it behaves like a normal collection, MongoDB treats time series collections as writable non-materialized views on internal collections that automatically organize time series data into an optimized storage format on insert (see Time Series Collections: Behavior).For this reason, indexing a time series collection involves creating an index in the underlying internal collection, instead of creating it on the visible collection. There are index types that are unsupported at this time: TTL, partial, and unique (see Time Series Collection Limitations: Secondary Indexes).For example, let\u2019s create a new timeseries collection:then create a document to insert:and let\u2019s insert three of those into the collection:if you then see the content of the collection, all three documents with identical content will be present:however, if you check the collection list, there is a mystery collection there:if you delve into the mystery collection, you\u2019ll see how the test collection is actually stored:so the test collection is just a view to the actual system.buckets.test. Inside the actual underlying collection, the three documents are stored in a single \u201cbucket\u201d. This is why as it currently stands, you cannot create a unique index on timeseries data.In conclusion, timeseries collection is a special collection type that is basically a view into a special underlying collection, thus it behaves differently from a normal MongoDB collection. This is done to allow MongoDB-managed storage of timeseries documents that is otherwise quite expensive to do if it\u2019s done using a regular MongoDB document. However, having this capability also comes with some caveats, namely the unique index limitation that you came across.Having said that, if you feel that having a secondary unique index is a must, you can create the collection in the normal manner, but lose the compactness of the timeseries collection storage. I suggest to benchmark your workload, and check if you can manage with a normal collection to store your data if the features you lose by using timeseries are important to your use case.Hopefully this is useful.Best regards,\nKevin\nCode:> db.createCollection(\"test\", { timeseries: { timeField: \"timestamp\" } } )\n> doc = {_id:0, timestamp: new Date()}\n> db.test.insertOne(doc)\n> db.test.insertOne(doc)\n> db.test.insertOne(doc)\n> db.test.find()\n[\n { timestamp: ISODate(\"2021-12-03T08:43:50.503Z\"), _id: 0 },\n { timestamp: ISODate(\"2021-12-03T08:43:50.503Z\"), _id: 0 },\n { timestamp: ISODate(\"2021-12-03T08:43:50.503Z\"), _id: 0 }\n]\n> show collections\ntest [time-series]\nsystem.buckets.test\nsystem.views\ntest> db.system.buckets.test.find()\n[\n {\n _id: ObjectId(\"61a9d8947dfd3e5b32de6144\"),\n control: {\n version: 1,\n min: { _id: 0, timestamp: ISODate(\"2021-12-03T08:43:00.000Z\") },\n max: { _id: 0, timestamp: ISODate(\"2021-12-03T08:43:50.503Z\") }\n },\n data: {\n _id: { '0': 0, '1': 0, '2': 0 },\n timestamp: {\n '0': ISODate(\"2021-12-03T08:43:50.503Z\"),\n '1': ISODate(\"2021-12-03T08:43:50.503Z\"),\n '2': ISODate(\"2021-12-03T08:43:50.503Z\")\n }\n }\n }\n]\ntestsystem.buckets.test"}, {"role": "assistant", "content": "Text:Thanks for your details explanations @kevinadi\nLike @Gorkem_Erdogan I was assuming timeseries collections would have a mechanisms to ensure uniqueness of timestamp/sensor data.\nIt\u2019s clearly a must have features for time series as network unstable connectivity may cause data to be sent multiple times.I think I\u2019ll go with this suggestions of querying data only through aggregation pipeline with a group stage to remove duplicates.\nBut it has impact in performance and complexity of development\u2026\nCode:"}, {"role": "assistant", "content": "Text:Any updates to this issue? We are building a time series collection for sensor data that might send duplicates and tried to require uniqueness on the timestamp but it still allows duplicates. I\u2019d love to leverage the performance improvements of the collection type but that a deal breaker if we can\u2019t prevent duplication.\nthanks,\nCode:"}, {"role": "assistant", "content": "Text:Same here. Planned to use time series collections, yet not being able to enforce uniqueness is a show stopper for us.\nCode:"}, {"role": "assistant", "content": "Text:Not a blocker for us, but I do wish we had at least a way to insert conditional greater than last timestamp. That would allow us to ingest with redundancy and make our pipeline more reliable. With the new index based time sorted queries for time series in 6.0, I\u2019d think this may not be too expensive to add?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Use map vs array of embedded documents? and tags: ['data-modeling']"}, {"role": "user", "content": "Text:I am using mongodb to store one-to-many relationship (similar to https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-many-relationships-between-documents/)Say a collection of blog posts with comments embedded in it. Which of the below approaches is recommended?Query Patttern:Write Pattern:Note:Approach 1: (array of embedded documents)Approach 2: (map of embedded documents)\nCode: {\n _id: 23, // postId in postgres\n comments: [\n {\n _id: 34, // commentId in postgres\n text: \"This is comment 34\",\n }, \n {\n _id: 67,\n text: \"This is comment 67\",\n }, \n ]\n }\n {\n _id: 23, // postId in postgres\n comments: {\n 34: {\n _id: 34, // commentId in postgres\n text: \"This is comment 34\",\n }, \n 67: {\n _id: 67,\n text: \"This is comment 67\",\n }, \n }\n }\n"}, {"role": "assistant", "content": "Text:The normal way for mongodb is to store data(unknown values) to arrays,\nand keys to be metadata(the known schema)The reasons for that is\n1)unknown fields cannot be indexed\nin your first approach if you want to index the comment_id,you can do it with\na multikey index,but in second how to make index on comment_id?\n2)Dynamic embeded documents are not well supported\nFor example we cant do get($$k)/remove($$k)/add($$k,$$v) in a fast way.\n(if key is a mongodb variable)If we have constant keys,meaning that we know them at the time we send the\nquery(not keys in mongodb variables),we can use pipeline stage operators,or even\nconstruct, query parts,but those are weird methods.Query pattern\nFor a given blog post, return comments with ids in a given array (around 1000 per second)Query patttern,first approach\n1)find post\n2)filter comments you need($filter on the comments map)\n*if you have like 10 average it will be very fastQuery pattern,second approach\n1)find post\n2)how you get the comments?\nyou contruct on driver something like the bellow,and you send the query after?This is weird wayI cant be sure the first is always the best,but i think in mongodb,data should go\ninto arrays,and schema should go into keys.\nCode: {\"$project\" {comments.100 1\n comments.20 1}\n ....\n }\n"}, {"role": "user", "content": "Text:How to make write pattern (Update/insert a comment with given id) work in case of array of embedded dcouments?\nGiven I always fetch comments by id, I am assuming Approach 2 will be more efficient than Approach 1 as I don\u2019t have to search through all documents (for large documents)\nCode:"}, {"role": "assistant", "content": "Text:Its easy to insert/or update a member(here a document) into an array.Query operators\nInsert new \u2192 $push\nUpdate existing \u2192 update a memberOr you can do a pipeline update\nInsert new \u2192 $concat\nUpdate existing \u2192 $mapYou dont need a pipeline update really,its for more complicated updates,query operators are fine.\nSee also thisI guess you know the post_id parent,of the comment that will be updated/insert,make an index\non post_id,and it will be very fast,you dont have like too many comments/post.If you dont know the post_id and you have only the comment_id that you want to update,you\ncan make a multikey index on comments._id,to find the post document fast.\nCode:"}, {"role": "user", "content": "Text:From what I read from MongoDB - Safely Upserting Subdocuments Into Arrays there is no single operator to atomically upsert into array of embedded documents.\nIs it still the case?I am worried about ending up with duplicate comments if two parallel threads try to insert($push) simulataneously\nCode:"}, {"role": "assistant", "content": "Text:MongoDB updates in 1 document they are atomic,you dont have to worry about anything.\n(all the changes that you do in 1 document,with 1 update,will be done all or nothing)MongoDB after >= 4.0 , we are now in MongoDB 5 supports trascactions so you dont have\nto worry about multi-document operations also.Also mongodb supports left joins with $lookup >= 3.2.This presentation is probably older,but the last slide shows how to push into an array,\nwith safely.You dont need transactions here or $lookup.See the above links also.\nIf you are new to MongoDB see the mongodb uni\nTo see all the videos you just enroll in the course,its free,and there is no need to pass the course,you can re-take the course if you want another time.\nCode:"}, {"role": "user", "content": "Text:I was not in favour of using the solution in presentation as it involves making multiple queries for making an upsert. Was wondering if there is a native way to do that in a single statement without encountering race conditions.I understand changes to a document are atomic in general. But was worried about ending up with two simultaneous $push resulting in two duplicate subdocuments in array.The stack overflow answer linked also does it in two steps (first steps removes the record from array if it exists and second step inserts). But still feel it is prone to race conditions.\nThe second solution does something similar but uses the aggregation pipeline. Do you know what lock is acquired by the read statement in a pipeline? i.e, if two servers have sent the same query to mongodb, does mongodb serialize the full pipeline or just the write parts of the pipeline?\nCode:"}, {"role": "assistant", "content": "Text:HelloWhen you send 1 query,you can change many things in the document and change will be\natomic.MongoDB offers pipeline updates also,that can do all sorts of complicated updates\nin 1 document.(you can send multiple queries also,but you need transactions to make them atomic)For an example of how to update an array with members documents see this queryIts atomic and its fast.It checks if new member => update,else add in the end of the array.\nIn your case if you already know if new or existing comment,you can make it even faster,\nand avoid the check.\nCode:"}, {"role": "assistant", "content": "Text:Hey Hasan. I\u2019m running into the same thing now re: deciding between structuring as nested objects vs. arrays. What did you end up going with? What do you recommend after dealing with this?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: ODBC Connection test not responding and tags: ['connector-for-bi']"}, {"role": "user", "content": "Text:mongo_error1536\u00d71440 97.9 KB\nI have installed mongo DB in Linux operating system(CentOS 7), I am configuring ODBC 32 bit connection in windows machine, when I test it is not responding, I have tried ODBC 64/32 bit and also tried with unicode and ascii option. I am not sure with what i am doing. I have also attached screenshot for connection details. Logs are not generating. Do i miss any configuration in ODBC like TLS or SSL?\nCode:"}, {"role": "assistant", "content": "Text:Welcome to the community @Vidya_Sagar_Reddy,The MongoDB ODBC Driver for BI Connector also requires a compatible version of the MongoDB Connector for BI to be installed and running.What are your installed versions of MongoDB ODBC driver, Connector for BI, and MongoDB server?Regards,\nStennie\nCode:"}, {"role": "user", "content": "Text:Sorry for Late reply,mongo --version\nMongoDB shell version v4.2.7\ngit version: 51d9fe12b5d19720e72dcd7db0f2f17dd9a19212\nOpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013\nallocator: tcmalloc\nmodules: none\nbuild environment:\ndistmod: rhel70\ndistarch: x86_64\ntarget_arch: x86_64cat /etc/os-release\nNAME=\u201cCentOS Linux\u201d\nVERSION=\u201c7 (Core)\u201d\nID=\u201ccentos\u201d\nID_LIKE=\u201crhel fedora\u201d\nVERSION_ID=\u201c7\u201d\nPRETTY_NAME=\u201cCentOS Linux 7 (Core)\u201d\nANSI_COLOR=\u201c0;31\u201d\nCPE_NAME=\u201ccpe:/o:centos:centos:7\u201d\nHOME_URL=\u201chttps://www.centos.org/\u201d\nBUG_REPORT_URL=\u201chttps://bugs.centos.org/\u201dCENTOS_MANTISBT_PROJECT=\u201cCentOS-7\u201d\nCENTOS_MANTISBT_PROJECT_VERSION=\u201c7\u201d\nREDHAT_SUPPORT_PRODUCT=\u201ccentos\u201d\nREDHAT_SUPPORT_PRODUCT_VERSION=\u201c7\u201dBI Connector Version: 2.13.4ODBC Driver: Tried with all possibilities 32/64 bit and 1.0/1.4(ascii/unicode)\nCode:"}, {"role": "assistant", "content": "Text:Thanks so much - I had a similar issue to this thread but it was because I didn\u2019t have the compatible version of the Connector for BI.\nCode:"}, {"role": "user", "content": "Text:@Marty_Zager, Could you please share me your compatible version for below list and let me try it out,\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m also facing the same issue, could you please share us detailed resolution here.So far have tried using Mongdb driver version 1.0 and 1.4 but no luck.Thanks,\nPavankumar\nCode:"}, {"role": "assistant", "content": "Text:The MongoDB BI Connector connects to the MongoDB server on port 27017 and will bridge the NoSQL nature of MongoDB and make its data visible as sort of virtual tables. ODBC driver then connects to the MongoDB BI Connector, typically on port 3307.\nso try 3307 instead 27017\nCode:"}, {"role": "assistant", "content": "Text:Please install MongoDB Connector for BI MongoDB BI Connector Download | MongoDB and then:\n\u201cC:\\Program Files\\MongoDB\\Connector for BI\\bin\\mongosqld.exe\u201d and:\n2021-12-02XXXXXXXXXXX I NETWORK [initandlisten] waiting for connections at 127.0.0.1:3307\nODBC will work fine on port 3307\nRegards \nCode:"}, {"role": "assistant", "content": "Text:i am facing same issue ,which is the compatible version of the connector for bi\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Issue when installing locally on Windows 10 and tags: []"}, {"role": "user", "content": "Text:The MSI installer ask if we want to install MonboDB as a service. Then, doesn\u2019t matter what value are entered it always end the following error message :The domain, user name and/or password are incorrect. Remember to use \u201c.\u201d for the domain if the account is on the local machine.563\u00d7557 17.7 KBit seems also described here :\nhttps://superuser.com/questions/1403332/invalid-domain-user-password-while-installing-mongodb-on-windows10And here :\nhttps://stackoverflow.com/questions/52092528/invalid-domain-user-password-while-installing-mongodb-on-windows10\nCode:"}, {"role": "assistant", "content": "Text:Please try your Windows username/password\nCode:"}, {"role": "user", "content": "Text:It works but I don\u2019t get why I should give those sensitive data to MongoDB and why other DBMS such as MySQL doesn\u2019t need it to install \nCode:"}, {"role": "assistant", "content": "Text:horrible, I want days where i could install software without giving so much information! For free edition? seriously mongodb, I don\u2019t even have my password setup in windows it is PIN! What a horrible UX, made account just to vent out\nCode:"}, {"role": "assistant", "content": "Text:Hello @Ruth_H_Gilbreath, and welcome to the MongoDB Community forums! The post you replied to talks about setting up mongod to run as a service. You are providing that info to the Windows OS to run the service. This is a Windows thing, not MongoDB. Note that this information is not sent to either MongoDB or Microsoft. The only time you\u2019re providing information directly to MongoDB is if you\u2019re creating an Atlas account, but then you\u2019re not installing MongoDB on your Windows system in that case.You can run MongoDB on Windows without setting it up as a service. Doing this however means that you have to manually run the mongod command before using the database.\nCode:mongodmongod"}, {"role": "assistant", "content": "Text:Using Windows Username/Password seems not working when we use a Windows email address to login as admin on our computer.I\u2019m using Windows 11, and I log on my computer with an outlook email address. Windows display as Username my firstname and my lastname with a space between.Neither Firstname alone, nor Firstname + Lastname, nor email address, work with MongoDB installation.\nCode:"}, {"role": "assistant", "content": "Text:What error you get with email address?\nTry domain/ID or firstname.lastname or give your I\u2019d with space in quotes\nIf none works you have to install it as not as service as Doug suggested above\nDisadvantage with this is you have to start mongod manually\nOther options don\u2019t use installer use command line install passing minimum parameters\nCheck mongo documentation\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Connections % of configured limit has gone above 80 and tags: ['connecting', 'monitoring']"}, {"role": "user", "content": "Text:Hello,\nI develop a small pet project which is mobile app in React Native. Noone uses it now. I have cluster M0 and today I got massive number of allerts saying Connections % of configured limit has gone above 80\n\nHere I found some advices: Closing Connections in MongoDB Atlas Clusters | MongoDB Atlas FAQAnd may questions are:\nCode:"}, {"role": "assistant", "content": "Text:I had the same thing happen to me starting at approximately 9:34pm PST. I\u2019m on the same tier (M0), have been using RealmSwift for prototyping on this cluster, and can no longer connect to it. (I can\u2019t even browse collections, or connect via shell.)I\u2019m very interested to know whats going on; M0 free tier doesn\u2019t support log downloading, so the tools for debugging this are few.\nCode:"}, {"role": "assistant", "content": "Text:Same problem for me with a M0 tier!\nCode:"}, {"role": "assistant", "content": "Text:Hey All, There is an issue with the proxy service for the free-tier only on Atlas - the team is working on a fix now, stay tuned.\nCode:"}, {"role": "assistant", "content": "Text:Appears to have been resolved - thanks @Ian_Ward !\nCode:"}, {"role": "assistant", "content": "Text:Hello,We are also getting the same issue on M0. The weird thing is that my machine was shut down and no one was using the app we are prototyping. Can\u2019t access the DB and collections anymore.\nCode:"}, {"role": "assistant", "content": "Text:Hello,\nToday I too received an alert from Mongodb Atlas for M0 cluster. According to Cluster overview there are 427 open connections, where 500 is the limit. There are only one or two users using our system currently that too aren\u2019t proactive users. There is very less possibility to open this number of connections as connection is not created every time, instead connection pooling is used. Can someone suggest what could be the reason for this?\nCode:"}, {"role": "assistant", "content": "Text:Is this still an open issue?I\u2019ve been receiving similar notifications on an m0 instance\nCode:"}, {"role": "assistant", "content": "Text:Same here, I have 40+ connections on a M0 even though the app is still in development and there are very few devices connected to it. How exactly does Realm manage connections to Atlas Clusters? Do we need to close the connections somehow?\nCode:"}, {"role": "assistant", "content": "Text:I got issue today, it\u2019s on our dev environment and there\u2019re very few devices (<5) connect to it\nCode:"}, {"role": "assistant", "content": "Text:M0 cluster has 80 connections even though the only app which is still in development is shutdown. How do we debug this? It is 2 years since the OP, but I don\u2019t see any concrete steps/actions/help.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: List of error codes and tags: []"}, {"role": "user", "content": "Text:Hello,ist there a list of error codes available?I know WriteConflict is code 112 and a DevideByZero is code 16608. But is there a complete list?The only source I was able to find was this one: error.rs.html -- sourceRegards,Christian\nCode:"}, {"role": "assistant", "content": "Text:I just found a list of error code in mongo-c-driver (by searching one of thecode in github), it\u2019s inside mongoc-error.h. But really, should have a better error code solution for cxx driver, or at least say something about the error code of c driver a bit.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: A complete Ansible role for MongoDB and tags: ['database-tools', 'backup', 'devops']"}, {"role": "user", "content": "Text:Hi,I\u2019m not sure whether this is allowed, but I\u2019d like to promote an Ansible role I developed for MongoDB, all versions. I hope this will ease the installation, configuration and management process of this application a lot for system engineers.It\u2019s fair to say that I\u2019m an experienced Ansible & system user. The main functionalities of the role are.The role can be found on my GitHub .\nCode:"}, {"role": "assistant", "content": "Text:Welcome to the MongoDB Community Forums @Kevin_Csuka!I moved this topic from \u201cOps and Admin\u201d to \u201cOpen Source Projects\u201d, but sharing and discussing projects using or related to MongoDB is definitely encouraged.Regards,\nStennie\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongo Data API and CORS and tags: ['data-api']"}, {"role": "user", "content": "Text:Hello, I\u2019m trying to query my Mongo DB on Atlas through the Data API, from the browser (with an Angular app) but I\u2019m blocked by CORS.\nI guess it\u2019s by design and the Data API is supposed to be consumed from server apps, not client apps, as the UI in the admin dashboard doesn\u2019t show anything that makes me think I can configure CORS, but just in case there\u2019s a way around this I\u2019d be glad to hear it.\nCode:"}, {"role": "assistant", "content": "Text:Hey Andrea - you\u2019re correct, currently it\u2019s blocked by CORS because we don\u2019t yet offer additional authentication and authorization options. Feel free to request it on Atlas: Top (1026 ideas) \u2013 MongoDB Feedback Engine and choose the \u2018Data API\u2019 category so we can gauge interest.Other ways to get around this is to wrap it in a backend or another managed service like Lambda or put an API gateway in front of it.\nCode:"}, {"role": "assistant", "content": "Text:Hi folks,For anyone who has a similar use case where CORS or a browser-only application environment currently prevents using the Data API (Preview), please watch/upvote the feature request to Support CORS from the Data API (MongoDB Feedback Engine).This feature request is currently under review, so any additional context on desired use case support would be helpful \u2013 start a new forum discussion using the data-api tag.In the interim, some alternative approaches to consider include:Putting an API gateway or serverless function in front of the Data API calls (as mentioned earlier in this topic).Using the MongoDB Realm GraphQL API:If you need an API from MongoDB Atlas right now that is not blocked by CORS, I suggest using the GraphQL API that is offered by MongoDB Realm. The Steps to generate this API involve -Using the Realm Web SDK.Regards,\nStennie\nCode:data-api"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Error \"Invalid scheme, expected connection string to start with \"mongodb://\" or \"mongodb+srv://\"\" and tags: ['node-js', 'mongoose-odm', 'atlas-cluster']"}, {"role": "user", "content": "Text:Hello,\nI have an error that blocks me, have you ever encountered this error?File .env =>index.jsError =>Thanks you in advance\nCode:DB_CONNECT = 'mongodb+srv://ID:PASSWORD@URL.mongodb.net/?retryWrites=true&w=majority';\nconst dotenv = require(\"dotenv\").config();\nmongoose.set(\"strictQuery\", false);\n\nmongoose.connect(process.env.DB_CONNECT, {\n\n useUnifiedTopology: true,\n\n useNewUrlParser: true,\n\n}).then(console.log('connect sucess to mongodb'))\n\nbot.ticketTranscript = mongoose.model('transcripts',\n\n new mongoose.Schema({\n\n Channel : String,\n\n Content : Array\n\n })\n\n)\nthrow new MongoParseError('Invalid scheme, expected connection string to start with \"mongodb://\" or \"mongodb+srv://\"');\n\nMongoParseError: Invalid scheme, expected connection string to start with \"mongodb://\" or \"mongodb+srv://\"\n"}, {"role": "assistant", "content": "Text:Hello @bill, Welcome to the MongoDB community forum,Can you please make sure by consol print this variable process.env.DB_CONNECT has the correct connection string?\nCode:process.env.DB_CONNECT"}, {"role": "user", "content": "Text:Hi, thanks you for answer,console displayWith \u2019 ';It\u2019s normal ?\nCode:'mongodb+srv://ID:PASSWORD@URL.mongodb.net/?retryWrites=true&w=majority';\n"}, {"role": "assistant", "content": "Text:It looks good, check out the documentation, I think you are missing something debug your code step by step,\nhttps://mongoosejs.com/docs/connections.htmlOut of the question, If you are using mongoose latest version then don\u2019t need to pass useUnifiedTopology: true, and useNewUrlParser: true in connection because by default it set true\nCode: useUnifiedTopology: true,useNewUrlParser: true"}, {"role": "assistant", "content": "Text:It\u2019s normal ?it notremove the quotes and if it still does not work remove leading and trailing spacss\nCode:"}, {"role": "assistant", "content": "Text:The trailing semicolon is probably erroneous too.\nCode:"}, {"role": "assistant", "content": "Text:[MONGOOSE] DeprecationWarning: Mongoose: the strictQuery option will be switched\nback to false by default in Mongoose 7. Use mongoose.set('strictQuery', false); if you want to prepare for this change. Or use mongoose.set('strictQuery', true); to suppress this warning.Invalid scheme, expected connection string to start with \u201cmongodb://\u201d or \u201cmongodb+srv://\u201dboth the error will be gone\nfirst use the\n// mongoose.set(\u2018strictQuery\u2019, true) in top\nand remove the extra space in the link of mondodb\nCode:strictQueryfalsemongoose.set('strictQuery', false);mongoose.set('strictQuery', true);"}, {"role": "assistant", "content": "Text:remove the \u2018;\u2019 from the last of .env file, and it will work\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Cant connect mongodb with node.js due to MongoServerSelectionError and tags: ['node-js', 'connecting']"}, {"role": "user", "content": "Text:When I try to connect mongodb with node I get this error.In picture\nIn many tutorial I have seen the solution of the problem can be found by whitelisting the ip address. but trust me I did but nothing happened.\n\nmongohelp2889\u00d7322 44.2 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Hello @Riyad_Sm and welcome to the MongoDB community forums. Can you use mongosh from that machine to connect to your Atlas cluster? Have you temporarily added 0.0.0.0/0 to the allow list to see if your Node app could connect? Are you behind a firewall or proxy that is not allowing your connection to go out to the MongoDB cluster?\nCode:mongosh0.0.0.0/0"}, {"role": "user", "content": "Text:I am a beginner . I never used Mongoose.As I said I am a beginner I just did what ever was in the documentation and I am confident I did not commit any error in the code.(In picture I have given My code)\nHow can I find out if I am behind a proxy or firewall?\n-Thanks\n\nmongohelp1841\u00d7527 27.1 KB\n\nCode:"}, {"role": "user", "content": "Text:I forgot to tag you @Doug_Duncan\nCode:"}, {"role": "assistant", "content": "Text:How can I find out if I am behind a proxy or firewall?If you are running the code from your house you probably don\u2019t have a firewall or proxy in place, especially if you\u2019re not sure. If you\u2019re running code from a work location however, you might be going through a proxy. You would have to ask your network team.Note that I am able to connect to that cluster (I can\u2019t do anything as I don\u2019t have the credentials), so it appears that you do indeed have the server open to the world for anyone to access.\nimage746\u00d7255 28.2 KB\nI would recommend restricting access only to the IP addresses that should be able to access this data. This is extremely important if you plan on having sensitive data stored in the cluster. I would recommend this even with authentication enabled.As for your code, I\u2019m not a Node developer (I\u2019m an admin/ops guy) so I\u2019m not sure if your code is valid or not.\nCode:"}, {"role": "user", "content": "Text:@Doug_Duncan Yes. I am using from home. My code is correct as far as I know. But still I am getting the error.!!\nCode:"}, {"role": "assistant", "content": "Text:I am not sure why you\u2019re getting a time out error. As you can see I was able to connect to the server so the server is accessible from anywhere. I just copied your code and was able to connect to the server without issue, so the code works as well.If you are getting a time out error from running the code then something on your end is blocking the connection from your machine to your atlas server.What happens if you run mongosh mongodb+srv://cluster0.hd6phlm.mongodb.net? Do you get a connection or do you get a timeout?\nCode:mongosh mongodb+srv://cluster0.hd6phlm.mongodb.net"}, {"role": "user", "content": "Text:I have no idea about mongosh. can you be more specific like what should I change in my code to connect? I would be grateful !\nCode:"}, {"role": "user", "content": "Text:@Doug_Duncan I used mongoose to connect, now I am getting this error:\nerror : MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you\u2019re trying to access the database from an IP that isn\u2019t whitelisted. Make sure your current IP address is on your Atlas cluster\u2019s IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/\nplease help!\nCode:"}, {"role": "assistant", "content": "Text:mongosh is a mongo shell\nA command line tool to connect to your mongodb\nBefore you connect with your app/mongoose check if you can connect by shell\nYou don\u2019t have add anything in your code\nFrom command prompt\nJust run mongosh \u201cyour connect string\u201d\nAre you using any VPN,anti virus or other softwares which may be blocking your connection or it could be firewall/proxy issues\nDid you try from another network or mobile hotspot just to check if it works or not on a different network\nCode:"}, {"role": "user", "content": "Text:@Ramachandra_Tummala I tried with mongoose with proper documentation. Nothing happened . And also I tried with my mobile network as well.still the same result.\nHow can I know that if is a proxy or firewall issue.? I did already try turning of my firewall though. How can I check if it is for proxy issue? Is there anyway to check that?\nCode:"}, {"role": "assistant", "content": "Text:What happens if you run mongosh mongodb+srv://cluster0.hd6phlm.mongodb.net ?What is the result of above?\nEven i can connect to your cluster like Doug_Duncan was able to connect\nYou have to contact your network admin if any firewall/proxy causing blocking\nCode:mongosh mongodb+srv://cluster0.hd6phlm.mongodb.net"}, {"role": "user", "content": "Text:I Don\u2019t have any network admin. I am using an local ISP here. What specific question should I ask to them about proxy? They Don\u2019t seem to know the answer though. And Where exactly should I put that part in my code?\nCode:"}, {"role": "assistant", "content": "Text:Do you have mongosh installed on your system?\nJust run mongosh from your terminal command prompt and show the output\nIf shell is available all you have to do is run below\n#mongosh mongodb+srv://cluster0.hd6phlm.mongodb.netAlso check this linkTo see if you\u2019re using a proxy/VPN online, go to\u00a0www.whatismyproxy.com. It will say if you\u2019re connected to a proxy or not.\n\nPC: Check under you\nCode:"}, {"role": "user", "content": "Text:I checked the link. It says no proxy was used.\nAnd also I Don\u2019t have mongosh installed and when i searched about that I found no article Where they show how to connect with mongosh with a node.js app. All I found was mongoose Which I already tried.\nCode:"}, {"role": "user", "content": "Text:@Doug_Duncan @Ramachandra_Tummala\nI tried with mongosh still got the error. I am sending you the screenshot\n\nmongo3956\u00d7222 7 KB\n\nCode:"}, {"role": "assistant", "content": "Text:As both I and Ramachandra can connect to your Atlas instance, there is nothing from the MongoDB Atlas side that is blocking your connection. This would mean that there is something on your side that is blocking the connections. If you have disabled the firewall and you\u2019re still not able to connect, you might be going through a VPN that is causing issues with you making a connection.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Riyad_Sm,Could you try the solution mentioned in the given thread https://www.mongodb.com/community/forums/t/error-in-connect-to-atlas/180790/7?u=kushagra_kesav\nimage.png3170\u00d7714 135 KB\nI hope it helps!Thanks,\nKushagra\nCode:"}, {"role": "user", "content": "Text:@Kushagra_Kesav @Ramachandra_Tummala @Doug_Duncan\nThanks for helping me my brothers.\nI solved the problem. Basically created another mongodb account with another gmail. And it worked! Maybe something was wrong with my previous gmail.\nPeace!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongorestore error \"don't know what to do with file... .bjson and .json\" and tags: ['database-tools', 'backup']"}, {"role": "user", "content": "Text:Hello,\nI am trying to use the command line cmd mongorestore to restore a backup of a mongoDB database I have. Will this restore not work with the Atlas Cluster? The original DB was just a normal localized server database.The error I am getting is:\ndon\u2019t know what to do with file \u201c/dev/channels.bson\u201d, skipping\u2026\ndon\u2019t know what to do with file \u201c/dev/channels.metadata.json\u201d, skipping\u2026Any help would help! Thanks\nCode:"}, {"role": "assistant", "content": "Text:It would help us help you if you provide the following information:Version of the Atlas cluster you are restoring to\nVersion of mongorestore you are using\nWas mongodump the same version?\nExact command you are running when you get this error.Usually this happens when you point mongodump at a subdirectory inside the full dump without specifying which namespace you want it to restore to, but I\u2019m just guessing - if you provide full details, it may be more clear what the issue is.Asya\nCode:mongorestoremongodumpmongodump"}, {"role": "assistant", "content": "Text:Use -db flag in your mongorestore command\nCode:"}, {"role": "assistant", "content": "Text:Thanks, it worked for me as well. But we need to pass command with -d insteed of -db.\nCode:"}, {"role": "assistant", "content": "Text:-d databaseName, now data will be restored in databaseName database.\nCode:"}, {"role": "assistant", "content": "Text:@Ramachandra_Tummala I am facing same issue, i have used below command to restoremongorestore --nsInclude dbname --ssl --host=\u201chostname:27017\u201d --usernam\ne= --password= --authenticationDatabase=admin --sslCAFile rds-combined-ca-bundle.pem --gzip /path/Can you please help me on this issue?\nCode:"}, {"role": "assistant", "content": "Text:just dbname will not work for nsInclude\n\u2013nsInclude=Try nsInclude=\u201cdbname.*\u201d\nCode:"}, {"role": "assistant", "content": "Text:Hi @Ramachandra_TummalaI have tried as you said the above command i am getting same error, Please find the below restore command for your reference.mongorestore --nsInclude=\"dbname\" --ssl --host=\u201chostname:27017\u201d --username=username --password=password --authenticationDatabase=admin --sslCAFile rds-combined-ca-bundle.pem /root/livedb/*\nCode:"}, {"role": "assistant", "content": "Text:Where is dbname.* in your commandIf your are restoring one collection\nnsInclude=dbname.collection_name\nIf it is full DB you have to use wildcard (*)\nPlease check this link having some examples\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Regex query with the Go driver and tags: ['golang']"}, {"role": "user", "content": "Text:I haveThe result is it returns ALL documents.I also hadsame resultbut alsoWhat do I have to do so the filter actually works?The mgo driver was straightforward, this driver is just awful!\nWhy are there bson.M bson.D bson.A bson.E\nWhy this overcomplication? Development time has increased 10fold with this driver compared to the mgo driver.\nI don\u2019t like SQL but lately I\u2019ve been considering to completely get rid of mongodb in favor of Postgresql, because the drivers available are actually straightforward and don\u2019t let the user jump through hoops of ridiculous data types.\nAlso you never answered my Rust question.\nCode:\t\t\tgames, e = h.service.GameRepo().Find(bson.M{\n\t\t\t\t\"slug\": bson.M{\"$regex\": primitive.Regex{\n\t\t\t\t\tPattern: \"^[0-9]\",\n\t\t\t\t\tOptions: \"i\",\n\t\t\t\t}},\n\t\t\t}, &options.FindOptions{\n\t\t\t\tSort: bson.D{{\"name\", 1}},\n\t\t\t})\n\t\t\tgames, e = h.service.GameRepo().Find(bson.D{{\n\t\t\t\tKey: \"slug\", Value: primitive.Regex{\n\t\t\t\t\tPattern: \"^[0-9]\",\n\t\t\t\t\tOptions: \"i\",\n\t\t\t\t},\n\t\t\t}}, &options.FindOptions{\n\t\t\t\tSort: bson.D{{\"name\", 1}},\n\t\t\t})\n\t\t\tgames, e = h.service.GameRepo().Find(bson.D{{\n\t\t\t\tKey: \"slug\", Value: bson.E{\n\t\t\t\t\tKey: \"$regex\",\n\t\t\t\t\tValue: primitive.Regex{\n\t\t\t\t\t\tPattern: \"^[0-9]\",\n\t\t\t\t\t\tOptions: \"i\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}}, &options.FindOptions{\n\t\t\t\tSort: bson.D{{\"name\", 1}},\n\t\t\t})\n"}, {"role": "assistant", "content": "Text:Hi @dalu,Can you let us know what the query looked like with mgo? We can try to help you translate it based on that information.\u2013 Divjot\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Error in react app: \"It looks like you are trying to access MongoDB over HTTP on the native driver port\" and tags: ['node-js', 'mongoose-odm', 'server', 'react-js']"}, {"role": "user", "content": "Text:I\u2019m totally new to node/mongodb\u2026 I\u2019m trying to retrieve data for my react app using Mongoose on Mac OS Catalina. Running mongod --version gives me 6.0.1. I have MongoDB running (I ran brew services start mongodb-community and my server consoles out Database connected: mongodb://localhost:27017/wheelPuzzles) but when I try to hit my GET endpoint using axios both in browser and Postman, I get:\nIt looks like you are trying to access MongoDB over HTTP on the native driver port.\nI\u2019ve been searching for 2 days now and cannot figure out why I\u2019m getting this error. What am I missing please? Can anyone help? Thanks!This is my error log, in case that helps:\nCode:mongod --version6.0.1brew services start mongodb-communityDatabase connected: mongodb://localhost:27017/wheelPuzzlesIt looks like you are trying to access MongoDB over HTTP on the native driver port{\"t\":{\"$date\":\"2022-11-06T16:41:17.247-05:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":22943, \"ctx\":\"listener\",\"msg\":\"Connection accepted\",\"attr\":{\"remote\":\"[::1]:59904\",\"uuid\":\"02520f8e-5a07-43b0-bfb2-64c48b07359a\",\"connectionId\":3,\"connectionCount\":1}}\n{\"t\":{\"$date\":\"2022-11-06T16:41:17.248-05:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":22944, \"ctx\":\"conn3\",\"msg\":\"Connection ended\",\"attr\":{\"remote\":\"[::1]:59904\",\"uuid\":\"02520f8e-5a07-43b0-bfb2-64c48b07359a\",\"connectionId\":3,\"connectionCount\":0}}\n{\"t\":{\"$date\":\"2022-11-06T16:41:17.248-05:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":22943, \"ctx\":\"listener\",\"msg\":\"Connection accepted\",\"attr\":{\"remote\":\"[::1]:59905\",\"uuid\":\"03a595a8-c6b8-4f9d-b3e9-9dbc2987c4f2\",\"connectionId\":4,\"connectionCount\":1}}\n{\"t\":{\"$date\":\"2022-11-06T16:41:17.249-05:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":22988, \"ctx\":\"conn4\",\"msg\":\"Error receiving request from client. Ending connection from remote\",\"attr\":{\"error\":{\"code\":17,\"codeName\":\"ProtocolError\",\"errmsg\":\"Client sent an HTTP request over a native MongoDB connection\"},\"remote\":\"[::1]:59905\",\"connectionId\":4}}\n{\"t\":{\"$date\":\"2022-11-06T16:41:17.249-05:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":22944, \"ctx\":\"conn4\",\"msg\":\"Connection ended\",\"attr\":{\"remote\":\"[::1]:59905\",\"uuid\":\"03a595a8-c6b8-4f9d-b3e9-9dbc2987c4f2\",\"connectionId\":4,\"connectionCount\":0}}\n"}, {"role": "assistant", "content": "Text:Welcome to the MongoDB community @TeeEm !The error message you are encountering indicates a misconfigured client is making a connection to your MongoDB deployment and sending HTTP requests instead of using the MongoDB Wire Protocol.How is your Axios app loading Mongoose to connect to your deployment? Can you share a snippet of code with any credentials redacted?I suspect you may have an axios.get() request that is trying to fetch a Mongoose model or MongoDB URI (which would result in this error).Regards,\nStennie\nCode:axios.get()"}, {"role": "user", "content": "Text:Thank you for your response Stennie!\nI\u2019m providing some code that\u2019ll hopefully help.This is my index.js:puzzle.js:and useEffect from App.js:\nCode:const app = require(\"express\")();\nconst PORT = 27017;\nconst express = require(\"express\");\nconst Puzzle = require(\"./src/models/puzzle.js\");\n\nconst mongoose = require(\"mongoose\");\nconst url = \"mongodb://localhost:27017/wheelPuzzles\";\nconst db = mongoose.connection;\nconst bodyParser = require(\"body-parser\");\nmongoose.connect(url, { useNewUrlParser: true });\n\ndb.once(\"open\", (_) => {\n console.log(\"Database connected:\", url);\n});\n\ndb.on(\"error\", (err) => {\n console.error(\"connection error:\", err);\n});\n\napp.use(express.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.listen(PORT, () => console.log(`IT'S WORKING on http://localhost:${PORT}`));\n\napp.get(\"/puzzle\", (req, res) => {\n Puzzle.aggregate([{ $sample: { size: 1 } }]).then((data) => {\n res.send(data);\n });\n});\nconst mongoose = require(\"mongoose\");\nconst Schema = mongoose.Schema;\n\nconst PuzzleSchema = new Schema({\n category: String,\n puzzle: String,\n});\n\nmodule.exports = mongoose.model(\"Puzzle\", PuzzleSchema);\nuseEffect(() => {\n axios\n .get(\"puzzle\")\n .then(function (response) {\n console.log(response);\n })\n .catch(function (error) {\n console.log(error);\n });\n }, []);\n"}, {"role": "user", "content": "Text:Bumping this question, in case anyone has any ideas about how to solve this error? Thanks!\nCode:"}, {"role": "assistant", "content": "Text:The problem is you are using the same port for Node/Express server as MongoDB default port : const PORT = 27017;\nReplace this constant with common port number used for Node/Express, such as 3000, 8000, 9000, etc.\nYou can then try to get data/resource from available endpoint (route) defined by your Node/Express app in the browser, like so :\nlocalhost:3000/puzzle\nassuming you are using 3000 as the port number for your Node server. If this works, the data fetching in your React app should work too.\nCode:"}, {"role": "user", "content": "Text:That was it! I changed the port for Node/Express to 8000 and it works beautifully now.Your response also helped me solve a second problem I had, where the front end wasn\u2019t connecting properly with the backend. I was using the wrong port in the URL for my API call too and changing the port number there fixed that problem also.Thanks so much for your help!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Cannot connect remotely to mongodb and tags: ['connecting']"}, {"role": "user", "content": "Text:I have followed several guides on installing and configuring mongodb. None are working, but I think I\u2019m close\u2026 I\u2019ve have managed to get to a point that I can connect to the db server from the local server using the following command:mongo -u user my_url/adminHowever, I\u2019m not able to connect to the server using the above command from a remote machine.I\u2019ve tried both with authentication enabled and disabled, and I\u2019ve tried setting the bindIP to 0.0.0.0, or adding the remote url after a comma, or commenting out the line but nothing worked. I also created the firewall rules for port 127 with the following commands:sudo iptables -A INPUT -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT\nsudo iptables -A OUTPUT -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPTWhat am I doing wrong? I am a beginner and it might be some stupid error \nCode:mongo -u user my_url/admin"}, {"role": "assistant", "content": "Text:remote machineBy remote, do you mean a different machine on the same network or a different machine from another location?If a different machine on the same network, it should work easily.As for the other case, you need to connect using the public IP address of the server. That is not necessarily the IP address of the machine running mongod, if behind a NAT router or VPN. You may find the current public IP using https://www.whatismyip.com/.\nCode:"}, {"role": "user", "content": "Text:Hi Steeve, thank you for your answer. I am using a VM from the data center of my university and in order to access it I need to be connected to a VPN from the same data center. As I am still connected to the VPN when I try to access the server on the VM, I guess that we should be on the same network. Nevertheless as none of what I read is working I am not sure.This is how I configured the mongo.conf file:I got 1.2.3.4 by running sudo ifconfig on the virtual machine and looking in the result for ens160When I run mongo -u user 1.2.3.4/admin on the VM it works, however when I do it from my pc I get this error:Am I using the wrong urls in the mongo.conf?\nCode: # network interfaces\n net:\n port: 27017\n bindIp: 127.0.0.1,1.2.3.4\nsudo ifconfigens160mongo -u user 1.2.3.4/adminMongoDB shell version v4.4.6\nconnecting to: mongodb://1.2.3.4:27017/admin?compressors=disabled&gssapiServiceName=mongodb\nError: couldn't connect to server 131.159.56.49:27017, connection attempt failed: NetworkTimeout: Error connecting to 131.159.56.49:27017 :: caused by :: Socket operation timed out :\nconnect@src/mongo/shell/mongo.js:374:17\n@(connect):2:6\nexception: connect failed\nexiting with code 1\n"}, {"role": "assistant", "content": "Text:The first thing I would try would be to bindIp:0.0.0.0. 1.2.3.4 might not be the address the correct address. The messageseems to indicate that there is some mapping happening between the client and the server.Then, Socket operation timed out might means a routing or firewall issue.Is the VM host your PC or another machine? If another machine then the 1.2.3.4 mapping might be different from the one on the VM host.\nCan you ping 131.159.56.49?\nWhere did you create the firewall rules?\nCode:connecting to: mongodb://1.2.3.4:27017/...\nError: couldn't connect to server 131.159.56.49:27017...\n"}, {"role": "assistant", "content": "Text:Is it really 1.2.3.4 or is that to obfuscate your actual ip address ?\nCode:1.2.3.4"}, {"role": "user", "content": "Text:It is my obscurated IP address\nCode:"}, {"role": "user", "content": "Text:I just noticed I didn\u2019t obscurate my IP address properly. 131.159.56.49 is 1.2.3.4\nCode:"}, {"role": "assistant", "content": "Text:Security through obscurity (Security through obscurity - Wikipedia) has never been favourable.And it does not help us helping you because we do not have the real facts.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Unable to connect to mongodb running in a docker container using Compass and tags: ['compass', 'containers']"}, {"role": "user", "content": "Text:I am running an empty mongodb instance in a docker desktop container using: docker run --name mongodb -d -p 64000:64000 mongoAm running Compass v1.30.1 and attempting to connect to the mongodb running on localhost using the connection string: mongodb://localhost:64000In the Compass UI, I receive the following visible error: connection to 127.0.0.1:64000 closedI have looked at the Compass log file and can see these entries:Also disabled my firewall temporarily, with no effect.Any help appreciated. Thanks in advance.\nCode:docker run --name mongodb -d -p 64000:64000 mongomongodb://localhost:64000connection to 127.0.0.1:64000 closed{\"t\":{\"$date\":\"2022-03-23T01:04:58.599Z\"},\"s\":\"I\",\"c\":\"COMPASS-CONNECT-UI\",\"id\":1001000004,\"ctx\":\"Connection UI\",\"msg\":\"Initiating connection attempt\"}\n{\"t\":{\"$date\":\"2022-03-23T01:04:58.602Z\"},\"s\":\"I\",\"c\":\"COMPASS-DATA-SERVICE\",\"id\":1001000014,\"ctx\":\"Connection 2\",\"msg\":\"Connecting\",\"attr\":{\"url\":\"mongodb://localhost:64000/?readPreference=primary&appname=MongoDB+Compass&directConnection=true&ssl=false\"}}\n{\"t\":{\"$date\":\"2022-03-23T01:04:58.616Z\"},\"s\":\"I\",\"c\":\"COMPASS-CONNECT\",\"id\":1001000010,\"ctx\":\"Connect\",\"msg\":\"Resolved SRV record\",\"attr\":{\"from\":\"mongodb://localhost:64000/?readPreference=primary&appname=MongoDB+Compass&directConnection=true&ssl=false\",\"to\":\"mongodb://localhost:64000/?readPreference=primary&appname=MongoDB+Compass&directConnection=true&ssl=false\"}}\n{\"t\":{\"$date\":\"2022-03-23T01:04:58.618Z\"},\"s\":\"I\",\"c\":\"COMPASS-CONNECT\",\"id\":1001000009,\"ctx\":\"Connect\",\"msg\":\"Initiating connection\",\"attr\":{\"url\":\"mongodb://localhost:64000/?readPreference=primary&appname=MongoDB+Compass&directConnection=true&ssl=false\",\"options\":*{\"monitorCommands\":true}*}}\n"}, {"role": "assistant", "content": "Text:Hello @kidcoconut\nWelcome to the community!!By default the MongoDB runs on port 27017, if you wish to change the port for your machine, you can use the command as:and login to the shell.\nFor Compass, the following URL would work:mongodb://localhost:64000Please let us know, if you are able to connect in the above mentioned way or if more information is needed from our end.Thanks\nAasawari\nCode:docker run --name -mongodb -d -p 64000:27017 mongo \ndocker exec -it mongodb\nmongodb://localhost:64000"}, {"role": "user", "content": "Text:Hi @Aasawari ,\nThankyou for the warm welcome.Some updates since my last note. In summary \u2026 I followed your tips with no success, then performed more analysis and troubleshooting. Things are working now, but I am left to think something was wrong with my Compass install and/or node_module libraries and dependencies.For simplicity, I recreated a new docker container for mongodb using 27018:27017. There was no change re ability to connect through Compass. Same connection-monitor-closed error and log.I then went into Compass and inspected the Dev Tools (toggle) and attempted to run some of the troubleshooting/test scripts. Loading the script did not work as there were errors/warnings re missing libraries under node_modules. I then shut everything down (docker/compass) and explicitly installed nvm and node (latest). I reinstalled Compass (win_msi), recreated the docker container for mongodb@27018:27017, and launched Compass. Success.I\u2019ll keep an eye on it and report back if I find anything else.Pls note for the benefit of others reading this, your sample commands need some adjustment to make them run properly (typos, missing flags, etc).Thanks again.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Realm refresh token expiry and customisation and tags: ['app-services-user-auth']"}, {"role": "user", "content": "Text:Hi Mongo RealmIn the Realm reference Authenticate HTTP Client Requests it states that access tokens expire 30 minutes after MongoDB Realm grants them.My question:Some background:Currently in my non-realm api I enforce the business logic that a user must re-authenticate once their subscription could end by setting the refresh token to expire when the users current subscription period ends (approx 1 month) and supplying the same refresh token to the user until it expires (do not regenerate another refresh token until current one has expired).\nCode:"}, {"role": "assistant", "content": "Text:@mba_cat If you use a custom JWT authentication you can set your own expiry which the system will respect - https://docs.mongodb.com/realm/authentication/custom-jwt/#mongodb-data-exp\nCode:"}, {"role": "user", "content": "Text:Thanks Ian if I use a custom JWT does this just customise the access token or can the refresh token be customised as well?I assume if I want to use the custom JWT option I would also have to build out my own with endpoints to handle login or is there a way to combine the email/password auth with my own custom JWTs?\nCode:"}, {"role": "assistant", "content": "Text:Refresh tokens have a lifetime of 60 days for username/password and the other builtin providers. If you want to customize anything that is where the custom JWT provider comes in. Although I\u2019d probably recommend a 3rd party provider rather than setting up your own auth endpoints as there are many out there that make it super easy.\nCode:"}, {"role": "user", "content": "Text:Hi IanI have been experimenting with Mongo Realm authentication and the custom JWT option.As far as I can see custom JWT only allows me to generate a custom JWT that can be used to log a user into Realm and create them - at which point Realm generates its own access and refresh JWT tokens for the user to to use to authenticate to the GraphQL endpoint.What I would like to do is to authenticate directly to the GraphQL endpoints using my own JWTs (which will have the custom expiry) or setup this custom expiry in the JWT tokens that Realm provides to the user.Is there a way to either:To clarify if I cannot set a custom expiry I would need to verify if the user is still a subscriber on each call they make to the endpoint which would slow everything down, if I can customise the tokens I am able to know that the user is a subscriber at least until their current refresh token expires.\nCode:"}, {"role": "assistant", "content": "Text:@mba_cat If you use a Custom JWT token and set the exp field then the Realm Cloud will respect that and no longer issue tokens for that user after the expiration limit has been reached. You cannot use your own tokens for requests to Realm Cloud - that would be a large security hole for the system. But we will respect the settings you pass from your custom JWT token.\nCode:exp"}, {"role": "user", "content": "Text:@Ian_Ward that does not appear to be the case. I generated a custom JWT token with an expiry in 1 hour, the refresh token returned to me expires in 1 month as per Mongo Realm default.How do I pass a setting from my custom JWT to Realm so that is respects the expiry?\nCode:"}, {"role": "assistant", "content": "Text:That sounds like unexpected behavior - please open a support ticket\nCode:"}, {"role": "user", "content": "Text:OkIn the meantime is there an alternative way to customise the Realm JWT tokens - by setting custom data etc?\nCode:"}, {"role": "assistant", "content": "Text:Any updates? It seems like the on the latest version I can still access the realm db after my jwt token expires\nCode:"}, {"role": "assistant", "content": "Text:A post was split to a new topic: I am trying to integrate Realm into my project using the authentication facility\nCode:"}, {"role": "assistant", "content": "Text:Hey \nCurrently we\u2019re still seeing the same behaviour with Custom JWTs.@Ian_Ward - do you know if there is some progress on this internally or if this was expected to be fixed?\nCode:"}, {"role": "assistant", "content": "Text:What behavior? Setting the expiration time of a token? That is released\nCode:"}, {"role": "assistant", "content": "Text:@Ian_Ward Sorry for the confusion. I meant the behaviour that mba_cat stated previously.We\u2019re using Custom JWT Authentication. Our tokens do include the required \u2018exp\u2019 field. According to the docs \u201cCustom JWT refresh token expiration is determined by the exp value of the user\u2019s JWT\u201d (https://www.mongodb.com/docs/atlas/app-services/users/sessions/#configure-refresh-token-expiration).Though the users refreshToken returned from app.logIn(Credentials.jwt(\"xxx\")) always is valid for 60 days. So it seems like it ignores the JWTs \u2018exp\u2019 field and actually uses the default refresh token expiration time instead.\nCode:expapp.logIn(Credentials.jwt(\"xxx\"))"}, {"role": "assistant", "content": "Text:You can now configure the expiration on the App Services configuration. It should be an option under the JWT auth provider\nCode:"}, {"role": "assistant", "content": "Text:Yes I saw that for non-Custom JWT Auth (and non-Anonymous Auth) it can be customized in the User Settings.But the linked docs states the exception that for \u201cCustom JWT refresh token expiration is determined by the exp value of the user\u2019s JWT.\u201dSo from my understanding this cannot be configured (which is good in this/our case) BUT instead should re-use the same \u2018exp\u2019 field value from the provided Custom JWT for the refresh token\u2019s \u2018exp\u2019 field as well, correct? Or do I get the docs wrong? \nCode:exp"}, {"role": "assistant", "content": "Text:You should be able to set the expiration in the UI and that will be respected. Is that not the case?\nCode:"}, {"role": "assistant", "content": "Text:Setting refresh expiry on the UI works for me, thanks!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDb doesnt' work with node.js 18.12.1 and tags: ['node-js']"}, {"role": "user", "content": "Text:os: win10;\nnode: 18.12.1\nmongodb: \u201c^4.11.0\u201dProgram which worked with node.js 16 doesn\u2019t work with node.js 18.\nEven the simplest sample:breaks with :\nMongoServerSelectionError: connect ECONNREFUSED ::1:27017\nat Timeout._onTimeout (D:\\TEST\\mongodb-test\\node_modules\\mongodb\\lib\\sdam\\topology.js:293:38)\nat listOnTimeout (node:internal/timers:564:17)\nat process.processTimers (node:internal/timers:507:7) {\nreason: TopologyDescription {\ntype: \u2018Unknown\u2019,\nservers: Map(1) { \u2018localhost:27017\u2019 => [ServerDescription] },\nstale: false,\ncompatible: true,\nheartbeatFrequencyMS: 10000,\nlocalThresholdMS: 15,\nsetName: null,\nmaxElectionId: null,\nmaxSetVersion: null,\ncommonWireVersion: 0,\nlogicalSessionTimeoutMinutes: null\n},\ncode: undefined,\n[Symbol(errorLabels)]: Set(0) {}\n}\nCode:const { MongoClient } = require('mongodb');\n\n// or as an es module:\n// import { MongoClient } from 'mongodb'\n\n// Connection URL\nconst url = 'mongodb://localhost:27017';\nconst client = new MongoClient(url);\n\n// Database Name\nconst dbName = 'myProject';\n\nasync function main() {\n // Use connect method to connect to the server\n await client.connect();\n console.log('Connected successfully to server');\n const db = client.db(dbName);\n const collection = db.collection('documents');\n\n // the following code examples can be pasted here...\n\n return 'done.';\n}\n\nmain()\n .then(console.log)\n .catch(console.error)\n .finally(() => client.close());\n"}, {"role": "assistant", "content": "Text:if it is only the nodejs version you have upgraded:\nCode:"}, {"role": "assistant", "content": "Text:The error ECONNREFUSED means no server is listening at the given address and port.The address mentioned::1:27017with the connection stringmongodb://localhost:27017means localhost is defined for IPv6. A localhost IPv4 would be 127.0.01. You have to make sure your mongod is listening to IPv6 interfaces or use 127.0.01 in your connection string rather than localhost.\nCode:mongodb://localhost:27017"}, {"role": "assistant", "content": "Text:localhost is defined for IPv6Wow! I completely missed that part.@Francek_Prijatelj you may check 2 forum posts below if you have time for a similar issue.As @steevej stated above, your localhost is bound to ::1 right now. It possibly is a recent change in your c:\\Windows\\System32\\drivers\\etc\\ file (an upgrade or a new program) that activated a ::1 localhost lineYou may remove/comment out it, or use 127.0.0.1 instead, as suggested.Econnrefused ::1:27017Follow up of Econnrefused ::1:27017\nCode:localhost::1c:\\Windows\\System32\\drivers\\etc\\::1 localhost127.0.0.1"}, {"role": "user", "content": "Text:Withit works fine.Sample code is copied directly from official github site https://github.com/mongodb/node-mongodb-native\nand it works with node16.\nI don\u2019t think localhost is changed globally, as it wouldn\u2019t work with node16 .\nMaybe there is a regression or a change in node@18.12.1 .\nCode:const url = 'mongodb://127.0.0.1:27017';\n"}, {"role": "assistant", "content": "Text:When we develop an app, the first assumptions we made might not be the best. And that choice must become a more generic one at some point to support the future. even if it breaks things, this is the right way we should choose.Node.js team made that decision change with this about a year ago: dns: default to verbatim=true in dns.lookup() by treysis \u00b7 Pull Request #39987 \u00b7 nodejs/node (github.com)One of developers #richardlau has this response on an issue ticket here https://github.com/nodejs/node/issues/40702#issuecomment-958157082For reference the change was #39987 \u2013 Node.js no longer re-sorts results of IP address lookups and returns them as-is (i.e. it no longer ignores how your OS has been configured). You can change the behaviour via the verbatim option to dns.lookup() or set the --dns-result-order command line option to change the default.Respect the OS configuration lies at the heart of the change. whether this configuration change was made by users themselves intentionally or an app changes it.Please check this for a priority discussion over IPv4 and IPv6\nnetworking - IPv4 vs IPv6 priority in Windows 7 - Super User\nCode:verbatimdns.lookup()--dns-result-orderRespect the OS configuration"}, {"role": "user", "content": "Text:To avoid confusion, it would be helpful to change localhost to 127.0.0.1 on the github page\nCode:"}, {"role": "assistant", "content": "Text:could be. But using localhost is a tradition for decades as using names rather than numbers is preferred by us human beings.Plus, IPv6 is relatively new and it is better to leave the job of dealing with problems that come together with using it to the users.It is actually a problem caused by OS developers who choose to activate IPv6 to be \u201clocalhost\u201d in the \u201chosts\u201d file without making it clear that it might break running programs. I was shocked to see this problem when I had it for the first time.Anyways, it is still a good exercise to show not everything goes to our expectations and we will have to dig deeper if we want to fix things. Fortunately, this one is not too deep to swallow us: use the number format, edit hosts file, or add flags.\nCode:localhost"}, {"role": "assistant", "content": "Text:3 posts were split to a new topic: TypeError: Object prototype may only be an Object or null: undefined\nCode:"}, {"role": "assistant", "content": "Text:I\u2019ve been facing this error from an hour,\nwhat if we want to create multiple collections with multiple schemas?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Nayab_RasoolIt is not clear what your problem is and does not seem to relate to this topic.Can you please give more details so we may have a better understanding!? and we maybe move it to a new discussion topic for broad attention.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to connect from AWS lambda function to mongo atlas by using an IAM role which is password less? and tags: ['security', 'serverless']"}, {"role": "user", "content": "Text:Can someone please explain the process in detail.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Jalaj_Kumar, thanks for posting to the Community Forums.Have you checked out this thread which poses a similar question and solution?\nCode:"}, {"role": "user", "content": "Text:@Pavel_Duchovny Why do we need to create a user and supply its key and secret access key when there\u2019s an alternative to directly connect with the AWS resource execution role like IAM role of the lambda function? The video Using AWS IAM Authentication with MongoDB 4.4 in Atlas to Build Modern Secure Applications - YouTube clearly explains this process should be password less and no credentials should be sent over to connect.\nCode:"}, {"role": "assistant", "content": "Text:As I understand it there are 2 types one is user/password like using the access key and secret key.And another one is by having the driver issuing kind of temp creds from aws api, but I haven\u2019t watched the presentation in full and I am not big expert with IAM auth\u2026\nCode:"}, {"role": "user", "content": "Text:Thanks. Is there someone who can help with this ?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Jalaj_Kumar,If you\u2019re connecting to a MongoDB Atlas cluster from your local machine, you will need to supply IAM credentials to the command line.However, if you\u2019re connecting to an Atlas cluster from AWS Lambda, Lambda will automatically retrieve temporary IAM credentials for you and make them accessible via environment variables (Using AWS Lambda environment variables - AWS Lambda).The three environment variables that your code will need are AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN. The secret access key will never be sent to Atlas or persisted by the driver (see the video for more details).For example the Atlas UI will publish an AWS IAM connection string that looks like this:If you\u2019re using Node.js on Lambda, you could then fill in the placeholders like this:const uri = mongodb+srv://${encodeURIComponent(process.env.AWS_ACCESS_KEY_ID)}:${encodeURIComponent(process.env.AWS_SECRET_ACCESS_KEY)}@my-cluster.8xebk.mongodb.net/myFirstDatabase?authSource=%24external&authMechanism=MONGODB-AWS&retryWrites=true&w=majority&authMechanismProperties=AWS_SESSION_TOKEN:${encodeURIComponent(process.env.AWS_SESSION_TOKEN)}Note that in order for this to work, you will need to have configured a database user (https://docs.atlas.mongodb.com/security-add-mongodb-users/) for AWS IAM Authentication, selecting \u201cIAM role\u201d from the \u201cAWS IAM Type\u201d drop-down menu.If you have additional questions or run into any problems, please let us know.Angela@MongoDB\nCode:mongodb+srv://:@my-cluster.8xebk.mongodb.net/myFirstDatabase?authSource=%24external&authMechanism=MONGODB-AWS&retryWrites=true&w=majority&authMechanismProperties=AWS_SESSION_TOKEN:\nmongodb+srv://${encodeURIComponent(process.env.AWS_ACCESS_KEY_ID)}:${encodeURIComponent(process.env.AWS_SECRET_ACCESS_KEY)}@my-cluster.8xebk.mongodb.net/myFirstDatabase?authSource=%24external&authMechanism=MONGODB-AWS&retryWrites=true&w=majority&authMechanismProperties=AWS_SESSION_TOKEN:${encodeURIComponent(process.env.AWS_SESSION_TOKEN)}"}, {"role": "user", "content": "Text:Hi @Angela_ShulmanThanks for the explanation. I tried using the below connection string from lambda function and receiving a timeout.I also have the lambda execution role arn added as a database user in my cluster.const MONGODB_URI = \"mongodb+srv://${encodeURIComponent(process.env.AWS_ACCESS_KEY_ID)}:${encodeURIComponent(process.env.AWS_SECRET_ACCESS_KEY)}@cluster/database?authSource=%24external&authMechanism=MONGODB-AWS&retryWrites=true&w=majority&authMechanismProperties=AWS_SESSION_TOKEN:${encodeURIComponent(process.env.AWS_SESSION_TOKEN)}\";\nCode:const MONGODB_URI = \"mongodb+srv://${encodeURIComponent(process.env.AWS_ACCESS_KEY_ID)}:${encodeURIComponent(process.env.AWS_SECRET_ACCESS_KEY)}@cluster/database?authSource=%24external&authMechanism=MONGODB-AWS&retryWrites=true&w=majority&authMechanismProperties=AWS_SESSION_TOKEN:${encodeURIComponent(process.env.AWS_SESSION_TOKEN)}\";"}, {"role": "assistant", "content": "Text:Hi @Jalaj_Kumar,Can you ensure that you have allowed IP access (https://docs.atlas.mongodb.com/security/ip-access-list/) and that there are no network connectivity issues?If you still have problems please create an in-app support chat session or open a support case (https://docs.atlas.mongodb.com/support/) so that we can help you with specifics in the context of your Atlas cluster and project. Please link to this forum topic and feel free to ask for me.Kind regards,\nAngela@MongoDB\nCode:"}, {"role": "assistant", "content": "Text:9 posts were split to a new topic: Task timed out after 5.01 seconds - MongoDB Atlas AWS connection issue\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Connection Reset Errors and tags: ['java', 'connecting']"}, {"role": "user", "content": "Text:Seeing an abundance of the below in a sharded cluster environment hosted in AWS. Any insight as to how to debug? Have tinkered with tcp keepalive on the servers (currently set to 120) and maxIdleTime on the client without any noticeable change.MongoDB Server Version: 4.4.2\nJava Driver: 'org.mongodb:mongodb-driver-reactivestreams:1.13.1\n\u2018io.reactivex.rxjava3:rxjava:3.0.3\u2019\nArchitecture: arm64\nCode:\"stack_trace\":\"java.util.concurrent.ExecutionException: com.mongodb.MongoSocketReadException: Exception receiving message\n at java.base/java.util.concurrent.CompletableFuture.reportGet(Unknown Source)\n at java.base/java.util.concurrent.CompletableFuture.get(Unknown Source)\n at com.creativeradicals.openio.pipeline.persist.feed.FeedMultiSaver.accept(FeedMultiSaver.java:107)\n at com.creativeradicals.openio.pipeline.persist.feed.FeedMultiSaver.accept(FeedMultiSaver.java:34)\n at com.creativeradicals.openio.rabbit.base.RequestConsumer.handleDelivery(RequestConsumer.java:42)\n at com.rabbitmq.client.impl.ConsumerDispatcher$5.run(ConsumerDispatcher.java:149)\n at com.rabbitmq.client.impl.ConsumerWorkService$WorkPoolRunnable.run(ConsumerWorkService.java:104)\n at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)\n at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)\n at java.base/java.lang.Thread.run(Unknown Source)\nCaused by: com.mongodb.MongoSocketReadException: Exception receiving message\n at com.mongodb.internal.connection.InternalStreamConnection.translateReadException(InternalStreamConnection.java:569)\n at com.mongodb.internal.connection.InternalStreamConnection.access$1200(InternalStreamConnection.java:76)\n at com.mongodb.internal.connection.InternalStreamConnection$5.failed(InternalStreamConnection.java:520)\n at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.failed(AsynchronousChannelStream.java:235)\n at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.failed(AsynchronousChannelStream.java:203)\n at java.base/sun.nio.ch.Invoker.invokeUnchecked(Unknown Source)\n at java.base/sun.nio.ch.Invoker$2.run(Unknown Source)\n at java.base/sun.nio.ch.AsynchronousChannelGroupImpl$1.run(Unknown Source)\n ... 3 common frames omitted\nCaused by: java.io.IOException: Connection reset\n at java.base/sun.nio.ch.UnixAsynchronousSocketChannelImpl.finishRead(Unknown Source)\n at java.base/sun.nio.ch.UnixAsynchronousSocketChannelImpl.finish(Unknown Source)\n at java.base/sun.nio.ch.UnixAsynchronousSocketChannelImpl.onEvent(Unknown Source)\n at java.base/sun.nio.ch.EPollPort$EventHandlerTask.run(Unknown Source)\n ... 1 common frames omitted\"}\n"}, {"role": "assistant", "content": "Text:See the discussion containing this suggestion and perhaps that will solve your problem\u2026\nCode:"}, {"role": "user", "content": "Text:Our application uses docker, and it looks like the version of Java we are on (OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.2+12) has patched the bug mentioned in that thread. Is there any other way to debug these constant connection reset errors and socket exceptions?\nCode:"}, {"role": "assistant", "content": "Text:Hmm, I don\u2019t know an easy way \u2026 maybe we can ask @Jeffrey_Yemin\nCode:"}, {"role": "assistant", "content": "Text:There\u2019s no straightforward way to determine the root cause of connection reset errors. It\u2019s not typically a driver bug that causes it. Rather, it\u2019s either something happening in the MongoDB server or in the network between driver and server. I would look first at MongoDB server logs to see if there are any clues there. It\u2019s possible that the server itself is closing the connection for some reason. If not, you\u2019ll need to involve an expert in network administration, perhaps to employ a tool like Wireshark to figure out what\u2019s happening, assuming that you can reproduce the error.One other thought: if you\u2019re able to test outside of Docker, that would be one way to rule that Docker itself as a contributing factor.\nCode:"}, {"role": "assistant", "content": "Text:Yes, simplification is a useful debugging tool.\nCode:"}, {"role": "user", "content": "Text:Our cluster is running on ARM64 CentOS machines in AWS. I see that the compatibility specs don\u2019t list CentOS under ARM64. Is it worth trying to switch the underlying Operating System to Ubuntu?\n.\nCode:"}, {"role": "user", "content": "Text:Seeing an abundance of these Client Disconnect errors reported by our routers:message: {\u201ct\u201d:{\"$date\":\u201c2021-01-19T17:47:02.856+00:00\u201d},\u201cs\u201d:\u201cD1\u201d, \u201cc\u201d:\u201cSHARDING\u201d, \u201cid\u201d:22772, \u201cctx\u201d:\u201cconn1749\u201d,\u201cmsg\u201d:\u201cException thrown while processing command\u201d,\u201cattr\u201d:{\u201cdb\u201d:\u201cadmin\u201d,\u201cheaderId\u201d:-697198149,\u201cerror\u201d:\u201cClientDisconnect: operation was interrupted\u201d}} c:SHARDING severity:7 ctx:conn1749 @timestamp:Jan 19, 2021 @ 12:47:22.867 host:mongodb-router-5 s:D1 @timegenerated:Jan 19, 2021 @ 12:47:03.144 host_ip:10.204.0.165 msg:Exception thrown while processing command severity_label:debug type:rsyslog id:22,772 attr.headerId:-697,198,149 attr.error:ClientDisconnect: operation was interrupted attr.db:admin program:mongos @version:1 port:34,092 facility_label:user t.$date:Jan 19, 2021 @ 12:47:02.856 pid:1606 logsource:mongodb-router-5syslogtag:mongos[1606]: facility:1 _id:CqjCG3cB7JtNHvfUX1ig _type:_doc _index:mongodb-2021.01.19 _score: -Any more ideas? These client disconnects are happening frequently. As i stated we\u2019ve followed the administrative guide to a tee. This is very disruptive to our application.\nCode:"}, {"role": "assistant", "content": "Text:It does not sound like a MongoDB problem, but rather, a network, hardware, or hypervisor problem with net connectivity. In 2017 I saw something like this and it turned out to be net connectivity between 2 subnets in separate wings of a factory installation. Have your network people looked at this?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Any alternative for '.find()' function in mongoose and tags: ['queries', 'node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:I am getting this error message when trying to run a callback function in the .find() mongoose method. Please suggest any alternative way to perform the operation done by the .find() method.\nCode:MongooseError: Model.find() no longer accepts a callback\n"}, {"role": "assistant", "content": "Text:Hi @Ankit_Patnaik,Welcome to the MongoDB Community forums The usage of callback functions has been deprecated in Mongoose 7.x. Therefore, if you were using these functions with callbacks, it is recommended to use either async/await or promises. If async functions do not meet your requirements, you can go for promises.I hope it helps!Best,\nKushagra\nCode:MongooseError: Model.find() no longer accepts a callback\nasync/awaitpromises// Before\nconn.startSession(function(err, session) {\n // ...\n});\n\n// After\nconst session = await conn.startSession();\n// Or:\nconn.startSession().then(sesson => { /* ... */ });\n"}, {"role": "assistant", "content": "Text:can you please tell me in which file i change?\nCode:"}, {"role": "assistant", "content": "Text:if you were finding for examplein the above, the List model is finding everything within the collection and you can tap on the results (lists) and then use the info the way you want. This solves that issue\nCode:List.find().then(function(lists){\n\n//Return results\n\n})\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB Authentication Failed With Spring Data URI and tags: ['java', 'connecting', 'containers', 'spring-data-odm']"}, {"role": "user", "content": "Text:when I try to connect spring boot application with the mongo-db container then the authentication failed exception has thrown.please refer to this link to get more details authentication-failed\nCode:2021-05-30 02:43:51.909 INFO 1 --- [nio-9090-exec-3] org.mongodb.driver.connection : Closed connection [connectionId{localValue:5}] to mongo-db:27017 because there was a socket exception raised by this connection.\n\n2021-05-30 02:43:51.924 ERROR 1 --- [nio-9090-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='benz', source='admin', password=, mechanismProperties=}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='benz', source='admin', password=, mechanismProperties=}] with root cause\n\ncom.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server mongo-db:27017. The full response is {\"ok\": 0.0, \"errmsg\": \"Authentication failed.\", \"code\": 18, \"codeName\": \"AuthenticationFailed\"}\n at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175) ~[mongodb-driver-core-4.2.3.jar!/:na]\n at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:358) ~[mongodb-driver-core-4.2.3.jar!/:na]\n at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:279) ~[mongodb-driver-core-4.2.3.jar!/:na]\n"}, {"role": "assistant", "content": "Text:nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-Have you tried with authSource in URI string?\nCode:nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-"}, {"role": "user", "content": "Text:yes, this is my URLmongodb://benz:14292@mongo-db/producer_db?authSource=admin\nCode:mongodb://benz:14292@mongo-db/producer_db?authSource=admin"}, {"role": "assistant", "content": "Text:Can you connect by shell or Compass using same connection details?\nCode:"}, {"role": "user", "content": "Text:yes, it works with shell\nCode:"}, {"role": "assistant", "content": "Text:Hi @Nafaz_M_N_M,We hope that the problem has been resolved. So, we can close this thread for now.!!\nIn case of any further issues or queries, please feel free to reach out by creating new post in a relevant category.All the Best,\nKushagra\nCode:"}, {"role": "user", "content": "Text:KushagraThe problem hasn\u2019t been solved, it works with shell but not with application. Do not close the thread before getting an answer\nCode:"}, {"role": "assistant", "content": "Text:Hi @Nafaz_M_N_M,Be sure, the thread will not be closed before getting resolved.\nI have moved the thread to a specific category and added some tags for broader visibility.All the Best,\nKushagra\nCode:"}, {"role": "assistant", "content": "Text:@Nafaz_M_N_M did you resolve the issue?\nI get the same error as you did. I can connect by shell using the same connection details, but not via Spring application.\nMy application.properties specify:\nspring.data.mongodb.authentication-database=admin\nCode:"}, {"role": "assistant", "content": "Text:UPDATE:\nI have now resolved my problem. This is what happend:\nI wanted to learn how to use a MongoDB instance from a Docker container instead of using my local MongoDB. I mapped the MongoDB container\u2019s port 27017 to the computers localhost 27017. When running the Spring Application, MongoDB seemed to respond. It was only when I tried to performe CRUD-operations that authentication failed. Finally I realized that the localhost 27017 was already in use by the local MongoDB. Thus, I mapped the MongoDB container to port 8094 on localhost, and now it seems to work fine. I hope this could be of any help to anyone.\nCode:"}, {"role": "assistant", "content": "Text:I seem to be having the same problem, I just fired a spring jpa mogo app and I have authentication issues when I try to perform any crud operation, I am running mongo on docker and I dont have any instances running locally also I checked my ports and one other app is using it. I am able to log on successfully when I using the mongo app.By the way running spring 2.7.4 with java 17 on an m1 macThe error I get is shown below2022-12-24 13:30:35.002 ERROR 86462 \u2014 [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path threw exception [Request processing failed; nested exception is org.springframework.data.mongodb.UncategorizedMongoDbException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName=\u2018adebola\u2019, source=\u2018onecard\u2019, password=, mechanismProperties=}; nested exception is com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName=\u2018adebola\u2019, source=\u2018onecard\u2019, password=, mechanismProperties=}] with root causecom.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): \u2018Authentication failed.\u2019 on server localhost:27017. The full response is {\u201cok\u201d: 0.0, \u201cerrmsg\u201d: \u201cAuthentication failed.\u201d, \u201ccode\u201d: 18, \u201ccodeName\u201d: \u201cAuthenticationFailed\u201d}\nCode:"}, {"role": "assistant", "content": "Text:Hello,\nDid you resolve this error? Im stuck on a similar error with code 18\nCode:"}, {"role": "assistant", "content": "Text:I faced similar error. And i resolve it by adding ?authSource=admin to the end of my mongo connection string.\nCode:?authSource=adminmongodb://:@:27017/image_hosting_db?authSource=admin\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Aggregation: Measuring performance and tags: ['aggregation', 'node-js', 'performance']"}, {"role": "user", "content": "Text:Hi - I\u2019ve recently completed M220 & M121. Excellent courses. I recommend both.I have several aggregation pipelines I\u2019ve developed. In general, they are slow and one exceeds 100MB available storage when I configure the settings a certain way.I really like how you can run explain() on find queries and get the execution time in milliseconds. I\u2019d like to do the same for aggregation, but I can\u2019t make that work. Any suggestions?Thanks - Peter.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Peter_Winer,You can run generate Explain Results for an aggregate operation using the mongo or mongosh shell as follows:Note that you can explain a find operation in the same fashion if you choose:The above indicates one of the three available verbosity modes: queryPlanner, executionStats and allPlansExecution.\nCode:// Find\ndb.collection.find({ ... }).explain();\n\n// Aggregate\ndb.collection.explain().aggregate([ ... ]);\nfinddb.collection.explain().find({ ... });\nqueryPlannerexecutionStatsallPlansExecution"}, {"role": "assistant", "content": "Text:I have several aggregation pipelines I\u2019ve developed. In general, they are slow and one exceeds 100MB available storage when I configure the settings a certain way.I\u2019m not sure what you mean by that - do you mean 100MBs RAM usage? I explain how that works here.Unless your pipelines spill to disk or are writing an output file they shouldn\u2019t be that slow. Can you give some examples of pipelines that are slow? If you are using MongoDB version 4.4 then explain with executionStats will show how long each stage took as well as how many documents entered each stage.Example:I walk through an example of this at the end of the talk I did for last year\u2019s MDB.live event but unfortunately the resolution of the code didn\u2019t turn out that good\u2026Asya\nCode:executionStatsdb.coll.explain(\"executionStats\").aggregate( [ ])\n"}, {"role": "user", "content": "Text:Asya - Thank you for responding. My database is hosted on MongoDB Atlas with version 4.2.13 Enterprise. Clearly I should upgrade to 4.4. The stats you referenced will be very helpful.The most important collection is a set of roughly 1.4MM timed events, growing about 25K events per day. I\u2019m implementing a dashboard that shows various views of the events, including time-based distributions.Users can configure the duration of the time series and how many divisions per day. The most fine grained option is 40 days of data, divided into 1-hour divisions, or 960 \u2018buckets\u2019 total.The $group stage is problematic. I use $addFields to give each event a \u2018bucket number\u2019, then group by bucket number. So, I am grouping the events into 960 separate buckets. I\u2019m very interested to know the time spent on this stage, and looking forward to trying 4.4 to discover this.I wonder if using $bucket would be more efficient? I could calculate the bucket boundaries in JavaScript and compose the $bucket stage. Then I would use $bucket to assign each event to the proper bucket, based on the time stamp, which is indexed. Does that make sense?I would be happy to share one or more of my pipelines, if you would review them. LMK and I\u2019ll send a couple of examples over. Best - Peter.\nCode:"}, {"role": "user", "content": "Text:Alex - Thank you for replying.I tried explain() as you recommended. It seems like the problem is with my MongoDB version, as pointed out by Asya in the next message of this thread. I am using 4.2.13 Enterprise hosted on MongoDB Atlas. I will upgrade to 4.4 in the next available time-window. This should help my effort significantly.Best - Peter.\nCode:"}, {"role": "assistant", "content": "Text:If you post the full pipeline that\u2019s slow, we can take a look and make suggestions about where it can be optimized. Of course having 4.4 explain output would be more enlightening but even 4.2 explain output will show some useful details about how the pipeline is executing and how it\u2019s using indexes (if any).Asya\nCode:"}, {"role": "user", "content": "Text:Asya - I updated to 4.4.4, also updated my local mongo shell and node.js driver. I now have execution stats available and i\u2019m finding areas to improve. In a few days after I\u2019ve fixed the \u2018low hanging fruit\u2019, I\u2019d like to take you up on your offer and send a couple of complete pipelines. Thank you! Peter.\nCode:"}, {"role": "assistant", "content": "Text:\nCode:"}, {"role": "assistant", "content": "Text:.explain does not working on vscode Is .explain works only on Terminal\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Email Confirmation Script for User Authentication via Email Address and tags: ['app-services-user-auth']"}, {"role": "user", "content": "Text:I\u2019m looking to move across from Firebase to MongoDB (for a number of reasons). But user authentication is a little more \u201cinvolved\u201d. Based on the Realm UI, I\u2019m required to enter an \u201cemail confirmation URL\u201d that should point to a page that contains an email confirmation script.I\u2019ve tried to look for some tutorials or guides on how to configure this as I\u2019m new to programming. Can anyone point me in the right direction please?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Anthony_CJ,The idea is you should set a link pointing to your application url endpoint where you would confirm the received token.Now the user is sended with an email by Realm system after registration the link he clicks should point to a place where you complete your registration with your sdk language.Here is the section for user confirmation flow for JS sdk (you should navigate to a similar docs for your sdk):Please let me know if this helps.Best\nPavel\nCode:"}, {"role": "user", "content": "Text:Thanks. I understand the process, what I don\u2019t know how to do is generate the email configuration script that I will locate at the email confirmation URL. I am building an iOS app so there\u2019s so web app.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Anthony_CJThis is more related to language specific redirect, you can also avoid email confirmation or do a function confirmation for your app.I would recommend looking into our IOS tutorial which shows email signup logic:\nhttps://docs.mongodb.com/realm/tutorial/ios-swift#enable-authenticationBest\nPavel\nCode:"}, {"role": "user", "content": "Text:Hi @Pavel_Duchovny. Thanks but I\u2019ve got that bit sorted. That\u2019s not what I\u2019m asking about. I\u2019m asking about the email confirmation URL and generating an email confirmation script.\nCode:"}, {"role": "assistant", "content": "Text:I have exactly the same question mark. It seems like you have to set up you own website with scripts to handle the confirmation link. Apparently in previous versions (Realm Cloud or Stitch) they provided this service for the clients but not anymore. I\u2019m trying to develop a desktop app with Realm, so I don\u2019t have a webserver, which could do that job. Thus this feature is not really useable for me.\nUsing custom functions to might be the answer, but because of a lack of examples I don\u2019t see how I still can validate that users provided a valid email (for password resets) .\nCode:"}, {"role": "assistant", "content": "Text:Hi @Anthony_CJ,I think its definitely possible to create a link which redirect to your ios app instead of a web page:iphone - ios url redirect from mail to app - Stack OverflowThis is a bit out of scope for realm per say.The code to confirm is:\nhttps://docs.mongodb.com/realm/ios/manage-email-password-users#confirm-a-new-user-s-email-addressAs I said if you don\u2019t want to use an email you can send the user SMS via twilio or email with a code and have the confirmation function input this code from email.Thanks\nPavel\nCode:"}, {"role": "assistant", "content": "Text:Hello, I was in the same boat as you and here are the steps I did to add email confirmation to my application. I am going to assume you have some knowledge with the MongoDB Realm website.Click on the \u201cEmail/Password\u201d provider.\n\nStep 12880\u00d71458 311 KB\nEnsure it is ON.\n\nStep 22880\u00d71458 363 KB\nInsert this code where you make the user sign up.\n\nStep 32880\u00d71458 567 KB\nThis is the super simple code that confirms your user when clicks on the \u201cconfirm email\u201d link that they get in their confirmation email.This line here \u201c\u201d allows us to use Realm as a global variable, and the rest is pretty self explanitory.\n** Ensure to put your own APP_ID **Now you have to host the script, this is super simple. Go to your Realm Apps home page and on the left hand side you should see a tab called \u201cHosting\u201d, click on it.\n\nStep 42880\u00d71458 528 KB\nThen put the code from the previous step into a file and upload that file by clicking \u201cUpload Files\u201d, and selecting that file.\n\nStep 52880\u00d71458 272 KB\nThis is the last step to this process, and the easiest, simple copy the link of the script,\n\nStep 62880\u00d71458 314 KB\n\nand add it to the email.\n\nStep 72880\u00d71458 368 KB\nThats all you need to do to have email confirmation with your iOS application using MongoDB Realm and Swift. The process for password reseting is very identical as well.\nCode:\n\n\n\n\nE-mail Confirmation\n\n\n\n

My Apps Name

\n

Thanks for choosing our app!

\n
\n\n\n"}, {"role": "assistant", "content": "Text:I would like to add here that copying the link and pasting it into the Email Confirmaion URL did not work for me because there was extra information included in the copied link. What did work was just adding the file name as a path to the web address like below:https://myappname.mongodbstitch.com/emailconfirmation.htmlI also wanted to note here that if you\u2019re using a React application you don\u2019t need to use vanilla javascript to create an email confirmation page. For example if you had an emailconfirmation route that made use of an emailconfirmation component you could simply paste the address of that route in your Email Confirmation URL like:https://myappname.mongodbstitch.com/emailconfirmationLastly I would like to mention that if the route uses capital letters it won\u2019t load the page in the browser. I also used the single page application option in the settings to run my app.\nCode:"}, {"role": "assistant", "content": "Text:The process for password reseting is very identical as well.@Sebastian_Gadzinski @thecyrusj13_N_A @Anthony_CJCan anyone please help me figure out how I can adapt Sebastian_Gadzinski\u2019s code for password reset?Would be very happy. Too bad that the documentation is so very lacking.\nCode:"}, {"role": "assistant", "content": "Text:@Nilom_N_AHi there, I got the solution:step 1: put a password-type text field on the website\nstep 2: add a confirm button for the user to click after he inputted the new password\nstep 3: when user clicks the confirm button callthats it. Show result like \u201cChange was successful. You may close this page now.\u201d\nCode:app.emailPasswordAuth\n .resetPassword(token, tokenId, passwordTextField.value)\n .then(() => displayResult('success'))\n .catch(err => displayResult('error', err))\n"}, {"role": "assistant", "content": "Text:Thank you for the reply.But I mean if the user forgot the password. Then a password confirmation mail has to be sent to his email adress. And the link inside the mail will lead to the site with the change password field.That will most likely need a script like the registration mail example above.\nCode:"}, {"role": "assistant", "content": "Text:@Nilom_N_A Yeah of cource, you use exactly the same script (HTML file) as posted above and then apply the 3 changes to it as I wrote. And remove the email confirmation content:from the script, obviously\nCode:app.emailPasswordAuth\n .confirmUser(token, tokenId)\n .then(() => displayResult('success'))\n .catch(err => displayResult('error', err))\n"}, {"role": "assistant", "content": "Text:thanks this really helped!I only had to change the link, like someone else said:\"What did work was just adding the file name as a path to the web address like below:https://myappname.mongodbstitch.com/emailconfirmation.html\"you saved me a lot of time Greetings Harri\u00ebt\nCode:"}, {"role": "assistant", "content": "Text:I updated the script above to work with the newest Realm Web SDK.\nCode:\n\n\n\n\nE-mail Confirmation\n\n\n\n

My Apps Name

\n

Thanks for choosing our app!

\n
\n\n\n\n"}, {"role": "assistant", "content": "Text:Thanks for the tutorial! \nDo I have to pay for Dedicated Clusters for hosting to be enabled and host the confirmation page?\nCode:"}, {"role": "assistant", "content": "Text:Hey Ciprian, no you do not have to pay for dedicated clusters for hosting to be enabled, I was using a shared cluster. You do have to have a Realm application as the hosting options are on the AppService tab.\nimage779\u00d7163 6.01 KB\nThere you can create a Realm Application and connect it to your cluster. Once you complete that process you should see the hosting option on the sidebar tab:\nimage605\u00d7907 33.8 KB\n\nCode:"}, {"role": "assistant", "content": "Text:its says that I have to upgrade it\n\nimage2661\u00d72026 155 KB\n\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: CursorNotFound after some time running large process and tags: ['python', 'sharding']"}, {"role": "user", "content": "Text:Hi,\nI\u2019m running a sharded cluster and I recently upgraded mongo from 3.0 to 4.2. Some programs that run previously without errors now raise CursorNotFound error in loops likewhere process can be quite time consuming and aggregation_query can return > 10000 values\u2026\nErrors come around 65mn from the beginning of the job (so much lower than the cursor timeout parameter, see below)I don\u2019t use explicit sessionsDB parameters cursorTimeoutMillis and localLogicalSessionTimeoutMinutes have already be \u201cugraded\u201d to the equivalent of 2 hours (7200000 and 120 respectively).How can I get more information (which systemLog component should I put to a debug level) ?\nAny idea of how to solve that ?Messages are like\nCursorNotFound: Cursor not found (namespace: 'my_db.my_collection', id: 5454438319793971081)\nIn which log (mongod or mongos) can I find this id ?Context is : mongoDB 4.2.3, pymongo 3.10.1\nCode:for rec in aggregation_query:\n process(rec)\nCursorNotFound: Cursor not found (namespace: 'my_db.my_collection', id: 5454438319793971081)"}, {"role": "assistant", "content": "Text:Hi @RemiJ, welcome!Errors come around 65mn from the beginning of the job (so much lower than the cursor timeout parameter, see below)That seems to be quite a long time to iterate, is it possible to refactor the application code to reduce the process iteration time ? Perhaps utilise $out to a temporary collection and spawn multiple processes.Cursor timeout is one of the possible reasons why the cursor could no longer be found. Could you ensure that the options were set correctly ? If an iteration of a cursor batch takes longer than the default cursor timeout of 10 minutes, the server deemed the cursor idle and will close it.Could you check on logs whether there\u2019s anything happening on the shard (i.e. replica set or config servers election) around the 65 minutes ?Regards,\nWan.\nCode:"}, {"role": "user", "content": "Text:Hi @wan,I had a look in the log. Actually, it comes from the sessions handler that kills the session after 30mn and not the 2 hours as specified by localLogicalSessionTimeoutMinutes=120. All the cursors attached to the session are deleted at same time.I updated my program to issue sessions refresh every 10mn so sessions don\u2019t expire before the end of processing.But now, when cursor in the main \u201cfor\u201d loop is a find and not an aggregate, I still get cursor timeout due to sharding\u2026 (cursor is active in (one) shard but expires in others)\nCode:"}, {"role": "assistant", "content": "Text:@RemiJ how did you resolve this issue? I\u2019m facing the same issue on a sharded cluster (version 4.0.28), java driver 4.7.0\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoTopologyClosedError: Topology is closed and tags: ['node-js']"}, {"role": "user", "content": "Text:#HelpWhen I am trying to connect to the MongoDB database it shows this error. Here I have submitted my index.js code and submitted also error reason before console.log(err) and after console.log(err). Can anyone suggest some techniques to solve this type of error?I am using a Wi-Fi (ISP) connection for browsing the internet and I had also tried mobile data but it cannot solve it.\n\nScreenshot (142)_LI1366\u00d7768 84.3 KB\n\n\nScreenshot (143)1366\u00d7768 104 KB\n\n\nScreenshot (144)_LI1366\u00d7768 94.5 KB\n\n\nScreenshot (145)_LI1366\u00d7768 111 KB\n\n\nScreenshot (146)_LI1366\u00d7768 90.1 KB\n\n\nScreenshot (147)_LI1366\u00d7768 109 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Hello @Md_Shihab, you can refer these MongoDB NodeJS Driver examples and try to use them as a guide for your coding - like, connecting to the database and performing some operations on the database.\nCode:"}, {"role": "assistant", "content": "Text:if the function is asynchronous check if you\u2019ve used the await method before the appropriate function\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: I don't receive all fields in Power BI from MongoDB Atlas using ODBC and tags: ['connector-for-bi']"}, {"role": "user", "content": "Text:Hello all,I use Power Bi to connect to MongoDB Atlas using ODBC connector : BI connector version 2.14 I don\u2019t receive all the columns from the Data Sources.I tried many time to refresh the connection, clean all the connection setting and isn\u2019t work ?\nI contact Microsoft support team and after checking they told that the problem come from the connector BI.Any one please can help me to solve this issues ? It\u2019s very Urgent.Thank you for your help.\nCode:"}, {"role": "assistant", "content": "Text:Can you see all columns from command line? (mongosqld or whichever tool you use)\nMay be permissions issue\nCheck data source settings\nCode:"}, {"role": "user", "content": "Text:Hi @Ramachandra_Tummala ,Thank you for your answer.\nYes I get all columns using MongoDB Compass with the same permissions.\nSo the problem is not come from Data Source Settings.Best,\nCode:"}, {"role": "assistant", "content": "Text:I am not referring to mongodb user permissions\nIn your Power BI under datasource tab something like global & file permissions radio tab must be there\nCode:"}, {"role": "user", "content": "Text:Yes, it\u2019s there :\n\nimage794\u00d7680 18.7 KB\n\nCode:"}, {"role": "assistant", "content": "Text:It could be filters or other settings causing issue\nWhat is the query you are using in editor\nCheck BI forums.You may get more helpA few of my columns are not comming into Power BI from the data source. I have selected \"get data\" and selected the table I would like from SQL Server I then\u00a0selected the table view on the left side of screen. I would expect to see the full...\nCode:"}, {"role": "user", "content": "Text:Hello @Ramachandra_Tummala,\nI already check all this but the problem is not come from Power BI, I had a discussion with Power BI support Team. And we conclude that the problem come more the MongoDB BI connector using ODBC.\nThis is why I am here to understand the issues.\nIt will be very helpful for me if you make me in contact with the Engineer Team.\nThank you.Best,\nCode:"}, {"role": "assistant", "content": "Text:HI, @MARWEN_FATNASSI\ndid you get any solution to this problem?when you update/add new data at MongoDB, it is not reflecteing in powerbi.\nand there is intermediate connector between mongo and powerbi i.e MongoDB bi connector\nCode:"}, {"role": "assistant", "content": "Text:Hello, same issue for me. Didn\u2019t found the solution. I use ODBC Connector on Power BI, works good, after that i add one collections but i can\u2019t see this collection on Power BI. I delete and recreate the ODBC Connector and refresh, but did\u2019nt work. Thx\nCode:"}, {"role": "assistant", "content": "Text:ThxI have having the exact same problem, and I have done all the steps you provided. I am experiencing this anytime I use the ODBC connector (Excel, Tableau), I can use the exact same permissions in Compass and see the missing collections.To me, this narrows down that is in fact the ODBC connector.How do I fix this???\nCode:"}, {"role": "assistant", "content": "Text:problemWere you able to resolve this? I\u2019m having the same problem.\nCode:"}, {"role": "assistant", "content": "Text:Does anyone know how to fix it? I had the same problem\nCode:"}, {"role": "assistant", "content": "Text:I have not found a solution. However, I opened a case with MongoDB about a week ago. They\u2019re currently investigating.\nCode:"}, {"role": "assistant", "content": "Text:@Shmub @Alice_Nguy_n @Jake_Shivers\ninstead of using the ODBC connector, I moved to an alternative option i.e Python\nBy using pymongo library in python, we can connect to the MongoDB collections and pull the data.\nyou just need a search on the internet - how to connect MongoDB to python using pymongo?\nonce the data is fetched to the python (i have used visual studio software)environment, you can copy-paste the same python code in the powerbi ,so the data fetches into powerquery.Run Python scripts in Power BI Desktop - Power BI | Microsoft Learn.you can read this document to activate python supported option in powerbi and to fetch the data.\nCode:"}, {"role": "assistant", "content": "Text:The problem here is probably the sampling size system variable on the BI Connector:If you are using MongoDB Atlas, this can be configured within the Atlas admin web interface in an optional configuration text box when you first set up your BI Connector. It\u2019s set my default to 100 but you can change this to 0 to force the connector to sample all the objects in a collection.\nCode:"}, {"role": "assistant", "content": "Text:This worked for me . change the value to 0 in atlasThank you @Thomas_Russell\nCode:"}, {"role": "assistant", "content": "Text:Hi, Having the exact same problem but in SSIS. We are losing metadata a bit randomly. We do not have \u201cMongoDB Atlas.\u201d I havnt been able to understand how the sample size can be set to 0. Someone who knows how to do it?\nCode:"}, {"role": "assistant", "content": "Text:I can confirm setting this to Zero within your Atlas configuration has resolved the problem. It may take a bit longer to pull down data given some collections are quite large and it\u2019s resampling all collections, however, that is better than it failing when attempting to work on the data.\nCode:"}, {"role": "assistant", "content": "Text:Hello @Seth_Helgeson how mush time it takes?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Docker-compose ReplicaSets - getaddrinfo ENOTFOUND and tags: ['replication', 'containers', 'devops']"}, {"role": "user", "content": "Text:As title suggests, I am using docker-compose running 3 mongo containers. I have attached the rs.status() log and also a screenshot of Studio3t to scan my ports for the members.\nrs.status()642\u00d7990 19.1 KB\n\n\nStudio3t722\u00d7823 49.4 KB\nI tried many variations of the connections string and ports based on the mongo documentation. I am new at this and still learning so any info helps!\nCode:"}, {"role": "assistant", "content": "Text:Hi @TheAdrianReza_N_A and welcome in the MongoDB Community !Have you set your IP addresses correctly in your bindIp network configuration? Did you include in there the IP address of your client in your 3 config files?If that\u2019s not it, could you please share your config file and your docker-compose.yml maybe so we have a bit more information to work with?Also \u2500 just to confirm \u2500 \u201cmongo-rs0-1\u201d, \u201cmongo-rs0-2\u201d and \u201cmongo-rs0-3\u201d are 3 different physical servers, correct?Cheers,\nMaxime.\nCode:bindIp"}, {"role": "user", "content": "Text:I do not believe I have done much in the network configuration. Feel free to suggest ways I can improve my docker-compose.yml file! It\u2019s a boilerplate mongo-rs docker container I found.And yes they are on 3 different servers.mongo.conf -replication:\noplogSizeMB: 1024\nreplSetName: rs0image597\u00d7838 16.8 KBReally appreciate the quick response! Let me know if there is anything else I can get you to help my situation!\nCode:"}, {"role": "assistant", "content": "Text:From my understanding, docker-compose is a tool that starts multiple containers that will work together on the same machine.So the way I understand it, your 3 \u201cmongo-rs0-X\u201d containers will be started on the same machine which makes me want to ask a simple question:Replica Sets are here for one main reason: High Availability in prod. If your 3 nodes depends on some piece of hardware they have in common (same power source, same disk bay, etc), it means you are not really HA because that piece of equipment can fail and bring all your nodes down, all at once. Which is a big NO NO in prod.That\u2019s the reason why it\u2019s a good practice to deploy your nodes in different data centers.I also see you are using --smallfiles which is a deprecated option which was only for MMapV1 which is gone now and --oplogSize 128 is definitely a terrible idea.So \u2500 based on this \u2500 I think you are trying to deploy a development or test environment here but then I really don\u2019t see the point of deploying 3 nodes on the same cluster. A single node replica set would most probably be good enough, no?Here is the docker command I use to start an ephemeral single replica set node on my machine when I need to hack something:I actually made an alias out of it which is in my ~/.bash_aliases file:And \u2500 because of the --rm option \u2500 I can just destroy the container and everything it contains (volumes included) with a simple:Is it what you were looking for or you really need to make these 3 nodes on the same machine work?Cheers,\nMaxime.\nCode:--smallfiles--oplogSize 128docker run --rm -d -p 27017:27017 -h $(hostname) --name mongo mongo:4.4.3 --replSet=test && sleep 4 && docker exec mongo mongo --eval \"rs.initiate();\"\n~/.bash_aliasesalias mdb='docker run --rm -d -p 27017:27017 -h $(hostname) --name mongo mongo:4.4.3 --replSet=test && sleep 4 && docker exec mongo mongo --eval \"rs.initiate();\"'\n--rmdocker stop mongo\n"}, {"role": "assistant", "content": "Text:Make sure that you have added replica set nodes in the host machine in etc/hosts file.\nJust like the below example -Note - 127.0.0.1 is your host machine and mongoset1, mongoset2 and mongoset3 are the nodes (members) of the replicaset.\nCode:127.0.0.1\tmongoset1 mongoset2 mongoset3\n"}, {"role": "assistant", "content": "Text:127.0.0.1\tmongoset1 mongoset2 mongoset3It\u2019s a nonsense to run 3 members of the same RS on the same machine. Running multiple data bearing mongod on the same machine shouldn\u2019t exist.The only exception to that rule would be if you are learning how RS works and you want to experiment while learning.\nCode:127.0.0.1\tmongoset1 mongoset2 mongoset3mongod"}, {"role": "assistant", "content": "Text:\" It\u2019s a nonsense to run 3 members of the same RS on the same machine. Running multiple data bearing mongod on the same machine shouldn\u2019t exist.\"How are we supposed to test transactions locally? We are already using docker compose for our local setup so not having this functionatliy would make it impossible to test Mongo Transactions. How are you testing your transactions? Are you using them? PS for the record I think this is the only reason you would want to setup replicas locally, or to mirror your hosted env for testing or for educational purposes. This feature does belong in mongod however.\nCode:mongod"}, {"role": "assistant", "content": "Text:Hey Maxine -The but why meme I almost find offensive because I am here ONLY because my team needs to test mongo transactions and it was YOUR TEAM that implemented in a way where they can only be tested with this replica configuration. So to come here, having spent my morning trying to get this to work and see that you meme the OP for doing this when you created the problem is \nCode:"}, {"role": "assistant", "content": "Text:I\u2019m sorry that you found that a bit offensive. I\u2019m being a bit sarcastic to REALLY explain why it doesn\u2019t make sense and get the point across. If you read my entire post, the answer and justification is in it.So \u2500 based on this \u2500 I think you are trying to deploy a development or test environment here but then I really don\u2019t see the point of deploying 3 nodes on the same cluster. A single node replica set would most probably be good enough, no?Here is the docker command I use to start an ephemeral single replica set node on my machine when I need to hack something:I explained in my answer why it\u2019s a bad idea and I also explained the solution: Single Node Replica Set.Transactions, Change Streams and a few other features in MongoDB rely on the special oplog collection that only exists in Replica Set setups. BUT you can set up a Single Node Replica Set that only contains a single Primary node and all the features will work just as good as in a 7 nodes Replica Set.So again, I reiterate:It\u2019s a nonsense to run 3 members of the same RS on the same machine.Use a Single Node RS instead. Same features but it\u2019s using 3X less ressources.\nCode:"}, {"role": "assistant", "content": "Text:Since the original question basically is \u201cHow can I access a replica set inside a docker network from the host\u201d, this solution might be useful:This will result in name resolve allowing access to mongo via localhost.somedomain.com both from inside docker and from the host (given the right exposed port)Note that the usual solution to this problem is \u201cmodify your local /etc/hosts file\u201d, which works too, but requires every dev/system in your organization to modify system files.\nCode:localhost.somedomain.comlocalhost.somedomain.com/etc/hosts"}, {"role": "assistant", "content": "Text:So in order to have a docker instance of a replica set MongoDB I need to modify the local etc/hosts file?\nHow has that behavior ever rolled to a production version?What about environments I do not have access to the system configuration (eg. CI/CD pipelines)?\nCode:etc/hosts"}, {"role": "assistant", "content": "Text:@MaBeuLux88 are you really a mongo employee? this is for testing purposes.@TheAdrianReza_N_A I believe it has something to do with replicaset config, you can try using bitnami images and try with the MONGODB_ADVERTISED_HOSTNAME as localhost, if my own tests are successful will post back.Sorry for the half response, but had to chime in to this nonsense with Maxime Beugnet!\nCode:"}, {"role": "assistant", "content": "Text:Hi @Marco_Maldonado and welcome in the MongoDB Community !Yes I am. It\u2019s written right here. I think I\u2019ll write a blog post about this because apparently nobody wants to hear that single node RS for a localhost dev environment is just fine. This is what I use daily to run a localhost dev environment:It works perfectly fine. I can use ACID transactions, change streams, \u2026If I want to keep the data, I can use a volume but I don\u2019t need to.Cheers,\nMaxime.\nCode:alias mdb='docker run --rm -d -p 27017:27017 -h $(hostname) --name mongo mongo:6.0.5 --replSet=RS && sleep 5 && docker exec mongo mongosh --quiet --eval \"rs.initiate();\"'\nalias m='docker exec -it mongo mongosh --quiet'\n"}, {"role": "assistant", "content": "Text:@Marco_Maldonado, Maxime is actually correct. You don\u2019t need a multinode cluster for testing or doing things in MongoDB.I don\u2019t really agree with the \u201cnonsense\u201d comment, but I do understand the sentiment because unless your test environment is intended to directly test and evaluate performance in an actual production environment to actually have full awareness of what impact things will have on an environment level, there really isn\u2019t as much of a need for a multinode replica set.@MaBeuLux88 otherwise I do agree with.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: SCRAM-SHA-1: (AtlasError) bad auth : Authentication failed while using mongodb api and tags: ['crud', 'data-api']"}, {"role": "user", "content": "Text:Hey @everyone\nI am trying to make crud api request using mongodb Data API. I am trying to make requests to my database to get data from the collections. I have whitelisted my IP and have added IP for connecting from anywhere. I have also added the API key to the request and in the body i am passing the\n{ \"dataSource\": \"Cluster0\", \"database\" : \"myFirstDatabase\", \"collection\" : \"phonelogsdetails\" } \nAny idea on why this autnentication error is coming and how to remove it\n\nimage1492\u00d7775 70.4 KB\n\nCode:{ \"dataSource\": \"Cluster0\", \"database\" : \"myFirstDatabase\", \"collection\" : \"phonelogsdetails\" } "}, {"role": "assistant", "content": "Text:It says bad authentication\nAre you using correct userid/pwd?\nCan you connect by shell?\nDoes your password has any special characters?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoServerError: not authorized on admin to execute command and tags: []"}, {"role": "user", "content": "Text:I am currently trying to run the following commend on my one atlas clusterI want use db.watch() to save change logs to the db. I am however getting the following error when trying to run the above commandThe cluster is on the Atlas M10 tier, in the AWS / Cape Town (af-south-1) region.Any help will be greatly appreciated.\nCode:use admin\ndb.runCommand( {\n setClusterParameter:\n { changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } }\n} )\nMongoServerError: not authorized on admin to execute command { setClusterParameter: { changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } }, lsid: { id: UUID(\"a33462c1-2419-4a35-947f-3ae2c7d9e127\") }, $clusterTime: { clusterTime: Timestamp(1669886477, 1), signature: { hash: BinData(0, C321D3B73BFD8D05FAD472201BEB5D2EFB037F23), keyId: 7139683256089182213 } }, $db: \"admin\" }\n"}, {"role": "assistant", "content": "Text:The user may not be having privileges to run this command or it may unsupported shell command on M10 cluster\nPlease check mongo documentation Atlas unsupported commands for different cluster Tiers\nCode:"}, {"role": "user", "content": "Text:The user I am using is set up as dbAdminAnyDatabase. I also had a look at the documentation for Atlas and could not see setClusterParameter under their unsupported commands.\nCode:"}, {"role": "assistant", "content": "Text:The user I am using is set up as dbAdminAnyDatabaseyour operation seems related to the cluster itself. this user has only given the privilege to work on databases, not the cluster itself.I am also not sure if you can change cluster settings within a shell. Your cluster sits on a cloud provider and is managed by MongoDB Atlas. Check the Atlas web interface first if you have access to those settings. (you would have 100% admin rights if you manage your own cluster)\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How can I fix error MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017? and tags: ['node-js', 'mongoose-odm', 'connecting']"}, {"role": "user", "content": "Text:Hello,How can I fix the MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 when I added the JSON for http://127.0.0.1:5000/v1/auth/register in postman?This is the JSON:Here\u2019s my User model:Then my authController.js\nCode:MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017http://127.0.0.1:5000/v1/auth/register{\n \"name\": \"john\",\n \"password\": \"secret\",\n \"email\": \"john@gmail.com\"\n}\nimport mongoose from 'mongoose';\nimport validator from 'validator';\n \nconst UserSchema = new mongoose.Schema({\n role: {\n type: String,\n trim: true,\n maxlength: 20,\n default: 'admin',\n },\n name: {\n type: String, \n required: [true, 'Please provide name'], \n minlength: 3, \n maxlength: 20,\n trim: true,\n },\n email: {\n type: String,\n required: [true, 'Please provide email'],\n validate: {\n validator: validator.isEmail,\n message: 'Please provide a valid email',\n },\n unique: true,\n },\n password: {\n type: String,\n required: [true, 'Please provide password'],\n minlength: 6,\n select: false,\n },\n lastName: {\n type: String,\n trim: true,\n maxlength: 20,\n default: 'lastName',\n },\n location: {\n type: String,\n trim: true,\n maxlength: 20,\n default: 'Tacloban City',\n },\n});\n \nexport default mongoose.model('User', UserSchema);\nimport User from '../models/User.js';\n \nconst register = async (req, res) => {\n try {\n const user = await User.create(req.body);\n res.status(201).json({user});\n } catch (error) {\n res.status(500).json({msg: 'there was an error'});\n }\n};\nconst login = async (req, res) => {\n res.send('login user');\n};\nconst updateUser = async (req, res) => {\n res.send('updateUser');\n};\n \nexport{register, login, updateUser};\n"}, {"role": "assistant", "content": "Text:Sorry if you already did this, but in case you didn\u2019t: can you connect to the database locally, using the mongosh? Also, Is it a replica set ? because mongoose also requires a few options.If you can include how you\u2019re connecting using mongoose odm (the mongoose.connect statement)\nCode:"}, {"role": "user", "content": "Text:Here is my mongoose script:Then the .env\nCode:import mongoose from 'mongoose';\n\nconst connectDB = (url) => {\n return mongoose.connect(url);\n};\n\nexport default connectDB;\nPORT=5000\nMONGO_URL=mongodb://127.0.0.1:27017/db_ras\n"}, {"role": "assistant", "content": "Text:@Jumar_JuatonThat looks fine to me as long as you remember .connect() method returns a promise, and errors should be caught.I\u2019m no specialist, but I\u2019d do the following checks:May also be good to know which platform are you running the server.\nCode:.connect()ps -ef | grep [Mm]ongodss -l | grep [Mm]ongodmongo"}, {"role": "user", "content": "Text:The process is running, but I need to run it using npm run start on root dir of the project. I\u2019ve tried running mongod and npm run start on root dir of the project, or even just mongod but it does return 500 error on postman. It only returns the MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 error if I run npm run start on root dir.Here\u2019s the complete repo of my code: https://github.com/jumarjuaton/repo-test\nCode:npm run startmongodnpm run startmongodMongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017npm run start"}, {"role": "assistant", "content": "Text:@Jumar_JuatonIt\u2019d be better if you share the output to see if the process is running. I send the data as JSON because afaik you\u2019re not processing urlencoded bodies.This is what I tested and the code runs. This is the request I run using linux lwp-request (alias POST):And gotI did minor modifications to the server, because of:It\u2019s as much as I can say with the data you provide. The is the server.js last lines are now:\nCode:echo '{\n\"name\":\"santi\",\n\"password\":\"123Santi\",\n\"email\":\"hello@pm.me\"}' | POST http://localhost:5000/api/v1/auth/register \\ \n-c 'application/json' \\\n-SE -t 3s\n201 Created\n\n{\n\"user\":{\n\"role\":\"admin\",\n\"name\":\"santi\",\n\"email\":\"hello@pm.me\",\n\"password\":\"123Santi\",\n\"lastName\":\"lastName\",\n\"location\":\"Tacloban City\",\n\"_id\":\"61ef18d9f053c87d81cd9937\",\"__v\":0}}\nconsole.log(error)const port = process.env.PORT || 5000;\n\n/*\napp.listen(port, () => {\n console.log(`Server is listening on port ${port}...`)\n});\n*/\n\nconst start = async () => {\n await connectDB(process.env.MONGO_URL);\n app.listen(port, () => {\n console.log(`Server is listening on port ${port}...`);\n });\n};\n\nstart().catch(e=>console.log(e))\n"}, {"role": "assistant", "content": "Text:@Jumar_Juaton did you find a solution to this error? I am facing the same error when testing my restapi on Postman. I can send a simple POST request to the serve.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to use multiple $lookup with arrays of objects and tags: []"}, {"role": "user", "content": "Text:let\u2019s consider i have some collection and the structures of data is look like thesepost col:user col:likesComments col:what i want to do is i have a userId (maybe more than one) that i want to search through all of posts (that is belong to the user) and get some data from posts collection and then $lookup to users collection that again get some data about user and after that every post has own postId (i converted _id to postId ). with postId i can $lookup to likeComments documents and get some data about any posts, but if a post don\u2019t have any likes or comments, all of my query that i wrote them gives me an empty array [] (not data at all just empty array) but if a post has at least one like and one comment, all of my query works find.what i expect is something like this:query:i know that my query is wrong but i can\u2019t find what\u2019s wrong here.\nCode:{\n _id: ObjectId(\"5fce0e137ff7401634bad2ac\")\n address: \"new york\"\n description: \"this is a great city\"\n image: \"images\\0.4644859674390589-gikiguk.jpg\"\n userId: \"5fcdcd8487e37216bc82171b\"\n}\n{\n _id: ObjectId(\"5fcdcd8487e37216bc82171b\")\n name: \"jack\"\n profile: {image: \"images\\0.4644859674390589-dofowfg.jpg\", description: \"be happy dude\"}\n email: \"test@test.com\"\n password: \"2a$12$gzRrY83QAjwLhdyvn3JQ2OcMj3XG65.BULva4cZqcuSxDhhMbSXCq\"\n}\n{\n _id: ObjectId(\"5fce0e191ff7301666kao2xc\")\n likes: {quantity: 1, likes: [{isActive: true, userId: \"5fcdcd8487c31216cc87886r\"}]}\n comments: {quantity: 1, comments: [{userId: \"5fcdcd8487c31216cc87886r\" , comment: \"awesome city\"}]}\n postId: \"5fce0e137ff7401634bad2ac\"\n}\nposts collection$lookupusers collectionpostId_idpostIdpostId$lookuplikeComments documents[] [\n {\n postId: '5fce0e137ff7401634bad2ac', //from post\n location: 'shiraz', // from post\n description: 'this is a greate city', // from post\n image: 'images\\\\0.4644859674390589-gikiguk.jpg', // from post\n userId: '5fcdcd8487e37216bc82171b', // from user\n name: 'mohammad', // from user\n profile: 'images\\\\0.6093033055735912-DSC_0002_2.JPG', // from user\n comments: { quantity: 1, comments: [{userId: \"...\", name: \"...\", profile: \"...\", comment: \"...\"}] }, // from likesComments and then lookup to users documets to get data about users that wrote comments\n likes: {quantity: 1, [{userId: \"...\", name: \"...\", profile: \"...\"}]} // from likesCommnets and then lookup to users documets to get data about users that liked the post\n }\n ]\ndb.collection(\"posts\")\n .aggregate([\n { $match: { userId: { $in: users.map(u => u) } } },\n {\n $project: {\n _id: 0,\n userId: { $toObjectId: \"$userId\" },\n postId: { $toString: \"$_id\" },\n location: \"$address\",\n description: \"$description\",\n image: \"$image\"\n }\n },\n {\n $lookup: {\n from: \"users\",\n localField: \"userId\",\n foreignField: \"_id\",\n as: \"userInfo\"\n }\n },\n { $unwind: \"$userInfo\" },\n {\n $project: {\n _id: 0,\n postId: 1,\n location: 1,\n description: 1,\n image: 1,\n userId: { $toString: \"$userId\" },\n name: \"$userInfo.name\",\n profile: \"$userInfo.profile.image\"\n }\n },\n {\n $lookup: {\n from: \"likes-comments\",\n localField: \"postId\",\n foreignField: \"postId\",\n as: \"likesComments\"\n }\n },\n { $unwind: \"$likesComments\" },\n {\n $project: {\n postId: 1,\n location: 1,\n description: 1,\n image: 1,\n userId: 1,\n name: 1,\n profile: 1,\n likes: {\n $map: {\n input: \"$likesComments.likes.likes\",\n as: \"item\",\n in: {\n $toObjectId: \"$item.userId\"\n }\n }\n },\n quantity: \"$likesComments.comments.quantity\",\n comments: {\n comments: {\n $map: {\n input: \"$likesComments.comments.comments\",\n as: \"item\",\n in: {\n $toObjectId: \"$item.userId\"\n }\n }\n }\n }\n }\n },\n {\n $lookup: {\n from: \"users\",\n localField: \"likes\",\n foreignField: \"_id\",\n as: \"likes\"\n }\n },\n { $unwind: \"$likes\" },\n {\n $lookup: {\n from: \"users\",\n localField: \"comments.comments\",\n foreignField: \"_id\",\n as: \"comments\"\n }\n },\n { $unwind: \"$comments\" },\n { $addFields: { quantity: \"$quantity\" } },\n {\n $project: {\n _id: 0,\n postId: 1,\n location: 1,\n description: 1,\n image: 1,\n userId: 1,\n name: 1,\n profile: 1,\n likes: [\n {\n userId: { $toString: \"$likes._id\" },\n name: \"$likes.name\",\n profile: \"$likes.profile.image\"\n }\n ],\n comments: {\n quantity: 1,\n comments: [\n {\n userId: { $toString: \"$comments._id\" },\n \n"}, {"role": "assistant", "content": "Text:Hi @mohammad_nowresideh,Welcome to MongoDB community!The query is very complex and resembles more of a relationsional schema for relational databases. This examples exactly why your schema design is not optimal for MongoDB and will put you in lots of troubles and complex aggregation.If your application expects to get and obejct like the following why not to structure the data this way:Whenever a user writes a post add all data to that document. Update likes and push comments into the arrays. If the comments array grows big add an extended document holding the rest of the comments.You can index the userid field for searches.Fixing this aggregation now will not avoid you from running into issues in the future, fixing the schema will.Thanks,\nPavel\nCode:{\n postId: '5fce0e137ff7401634bad2ac', //from post\n location: 'shiraz', // from post\n description: 'this is a greate city', // from post\n image: 'images\\\\0.4644859674390589-gikiguk.jpg', // from post\n userId: '5fcdcd8487e37216bc82171b', // from user\n name: 'mohammad', // from user\n profile: 'images\\\\0.6093033055735912-DSC_0002_2.JPG', // from user\n comments: { quantity: 1, comments: [{userId: \"...\", name: \"...\", profile: \"...\", comment: \"...\"}] }, // from likesComments and then lookup to users documets to get data about users that wrote comments\n likes: {quantity: 1, [{userId: \"...\", name: \"...\", profile: \"...\"}]} // from likesCommnets and then lookup to users documets to get data about users that liked the post\n }\n"}, {"role": "user", "content": "Text:Thanks @Pavel_Duchovny,\nYes, you\u2019r right this is very complex, but to have clear data i separated the additional information to another collection. in the next project i\u2019ll do all of that in the one document.\nin my current project if i want to change my schema i have to change a lot of code and this is very cumbersom. but may i ask you what is the query of this data?\nplease.\nCode:"}, {"role": "assistant", "content": "Text:Hi @mohammad_nowresideh,Not sure I understand the question.If you cannot change the schema I would do 3 indexed queries rather than managing this very long 3 lookup query with all the transformation.Query posts, query users, query comments.Thanks\nPavel\nCode:"}, {"role": "user", "content": "Text:Thank you for answering my question @Pavel_Duchovny\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB disk space increases abruptly - WiredTigerLAS.wt and tags: ['performance']"}, {"role": "user", "content": "Text:Hi,\nwe are using latest MongoDB recently. But after changing to the latest MongoDB we are facing issue with file system utilization. MongoDB file WiredTigerLAS.wt abruptly using more than the 70% of disk space. So, Utilization of the disk space become 100% sometime and downs DB automatically. Please help us to understand the issue and provide a solution for this issue.MongoDB Version : 4.2.2\nNo. of application point MongoDB Instance : 2\nFile Name: WiredTigerLAS.wtCase 1\nData Growth: 265GB in 20 HoursCase 2:\nData Growth: 395GB in 12 Hours\nCode:"}, {"role": "assistant", "content": "Text:Not something I\u2019ve come across. So this is just my 5 minute note:This is worth a read IMO\nFrom Percona:Note for readers coming here from web search etc: The typical symptoms are suddenly you notice that the WiredTigerLAS.wt file is growing rapidly. So long as the WT cache is filled to it\u2019s maximum the file will grow approximately as fast as the Oplog GB/hr rate at the time. Disk utilization will be 100%, and the WiredTigerLAS.wt writes and read compete for the same disk IO as the normal db disk files. The WiredTigerLAS.wt never shrinks, not even after a restart. The only way to get rid of it is to delete all the files and restart the node for an initial sync (which you probably can\u2019t do until the heavy application load stops).Don\u2019t forget: The initial cause is not primarily the software issue - the initial cause is that the application load has overwhelmed replica sets node\u2019s capacity to write all the document updates to disk. The symptom manifests on the primary, but it may be lag on a secondary that is the driving the issue.You have this option: https://docs.mongodb.com/manual/reference/configuration-options/#storage.wiredTiger.engineConfig.maxCacheOverflowFileSizeGBBut pay close attention to what happens when this is non-zero:If the WiredTigerLAS.wt file exceeds this size, mongod exits with a fatal assertion. You can clear the WiredTigerLAS.wt file and restart mongod .Hopefully someone else can give some knowledgeable input.\nCode:WiredTigerLAS.wtmongodWiredTigerLAS.wtmongod"}, {"role": "user", "content": "Text:Thanks much chris. I will try to control this file size by configuring maximum size as mentioned.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Visva_Ram,What sort of deployment do you have (standalone, replica set, or sharded cluster)? If you have a replica set or sharded cluster, can you describe your the roles of your instances in terms of Primary, Secondary, and Arbiter and also confirm whether you are seeing the LAS growth on the Primary, Secondaries, or both?WiredTigerLAS.wt is an overflow buffer for data that does not fit in the WiredTiger cache but cannot be persisted to the data files yet (analogous to \u201cswap\u201d if you run out of system memory). This file should be removed on restart by mongod as it is not useful without the context of the in-memory WiredTiger cache which is freed when mongod is restarted.If you are seeing unbounded growth of WiredTigerLAS.wt, likely causes are a deployment that is severely underprovisioned for the current workload, a replica set configuration with significant lag, or a replica set deployment including an arbiter with a secondary unavailable.The last scenario is highlighted in the documentation: Read Concern majority and Three-Member PSA and as a startup warning in recent versions of MongoDB (3.6.10+, 4.0.5+, 4.2.0+).I will try to control this file size by configuring maximum size as mentioned.The maxCacheOverflowFileSizeGB configuration option mentioned by @chris will prevent your cache overflow from growing unbounded, but is not a fix for the underlying problem.Please provide additional details on your deployment so we can try to identify the issue.Regards,\nStennie\nCode:WiredTigerLAS.wtmongodmongodWiredTigerLAS.wtmajoritymaxCacheOverflowFileSizeGB"}, {"role": "user", "content": "Text:Thanks Stennie,I am using standalone setup, but the single MongoDB instance used by two homogenised application by pointing different database.We were used old version of MongoDB 3.4.17. In that, i haven\u2019t seen this kind issues.In this, Are you saying? I am overloading the MongoDB?\nIf so, Performance can be degaraded, why the caching size is keep on increasing, That I don\u2019t understand.What is the purpose of WiredTigerLAS.wt in MongoDB?I am not able to accept that disk usage will keep on increase and down automcatically.If So, then How i can calculate the load that can be given to MongoDB to avoid this issue. Please comment. Thanks.\nCode:"}, {"role": "assistant", "content": "Text:Hey there,\nI have the exact same problem with a single mongo instance.I\u2019m doing many bulkWrites one after the other and in parallel and for some cases the file size increases until the entire disk gets full and Mongo crash.I think me and many others need a more definite answer on how can I tell how much writing operation could cause this and how to limit my load on mongo, it\u2019s really hard to just \u201cguess\u201d the numbers here. Also I think it\u2019s weird that mongo can\u2019t handle the load in a better way or clear this file after the load has finished.\nCode:"}, {"role": "assistant", "content": "Text:Yeah, I also think the database should handle it in a more elegant way. DONOT let users see strange things, though it\u2019s about internal implementation.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB timeout error and tags: ['aggregation', 'queries', 'java', 'mongodb-shell']"}, {"role": "user", "content": "Text:I am facing timeout error when i am fetching same collection simultaneously. Could you help me fix this issue ? i have mentioned the error belowTimed out after 30000 ms while waiting for a server that matches com.mongodb.client.internal.MongoClientDelegate$1@b586e86. Client view of cluster state is {type=REPLICA_SET, servers={, type=UNKNOWN, state=CONNECTING}, {address=, type=UNKNOWN, state=CONNECTING}, {address=](), type=UNKNOWN, state=CONNECTING}]\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: \"_id\" field mapped to null || PojoCodecRegistry and tags: ['java']"}, {"role": "user", "content": "Text:Hi,I am using PojoCodecRegistry (BSON library) and need to map the the \"_id \" field of the Mongo DB document to user defined POJO field.However, the \u201c_id\u201d field is getting mapped to null. I have a property named as :I am using mongo java 4.0 driver and JAVA 8\nCode:"}, {"role": "assistant", "content": "Text:Hello Aditya,Can you provide details about how you are mapping the _id field - please include your Pojo class with the _id field mapping.However, the \u201c_id\u201d field is getting mapped to null. I have a property named as :Also, please include code you had tried to build the Pojo object and insert into the collection.\nCode:_id_id"}, {"role": "user", "content": "Text:Thanks So very much for acknowledging the concern.\nThe POJO class is something like below ::package org.mongo;//imports@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class Student {\npublic Student() {\t\n}}Basically this error is occurring when the BSON is deserialized to Java Object. _id field is mapped to null. Rest all other fields are mapped properly.Please let me know how to solve this problem.\nCode:@BsonProperty(\"_id\") \n@JsonProperty(\"_id\")\nprivate ObjectId _id;\n\nprivate String name;\nprivate int age;\nprivate int courseCount;\nprivate String email;\nprivate boolean isVerified;\nprivate ArrayList hobbies;\nprivate ContactDetails contactDetails;\nprivate ArrayList marks;\n\n// Getters and Setters\n\n// toString() method\n"}, {"role": "assistant", "content": "Text:Basically this error is occurring when the BSON is deserialized to Java Object. _id field is mapped to null.The Pojo class is good.You can create Pojo objects and insert into a MongoDB collection as documents and retrieve them - without problem. All this using the default driver created ObjectId.You can post the code related with creating the object (new Student(), setting the properties, etc.,), how you are inserting and retrieving.Also, see code examples at: MongoDB Java Driver - POJOs.\nCode:ObjectIdnew Student()"}, {"role": "assistant", "content": "Text:Is there any solution for the above issue I have the same problem too. Thanks\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to sum up one record per day for one month? and tags: ['aggregation']"}, {"role": "user", "content": "Text:Hi\nI\u2019m trying to do to aggregate, sum up values in a month, but i only want to sum 1 entry per day, i tried to use $limit before the group but only get 1 entry return.Thanks.\nCode:[\n { \n $match: \n { \n \"fPort\": 60,\n \"rxInfo.time\": \n { \n \"$gte\": \"2020-12-01T00:00:00.000000Z\", \n \"$lte\": \"2020-12-31T59:59:59.935Z\"\n }\n }\n },\n { $limit: '1' }, ///// This only returns 1 record and not 1 per day.\n { \n $group: \n { \n _id: \"9cd9cb00000124c1\",\n \"Total\": \n {\n \"$sum\": \"$object.TotalDaily\" \n }\n }\n }\n]\n"}, {"role": "assistant", "content": "Text:Hello @Q_Lion, Welcome to MongoDB Developer Community,As i can understand your question, you need to get count of documents yearly or monthly or daily,You can use $year, $month, $dayOfMinth Date Expression Operators.Example for Daily document count,Example for Monthly document count,You can replace yourDateFieldName to your collection field, and put your $match stage before this $group stage.\nCode:[{\n $group: {\n _id: {\n year: { $year: \"$yourDateFieldName\" },\n month: { $month: \"$yourDateFieldName\" },\n day: { $dayOfMonth: \"$yourDateFieldName\" }\n },\n Total: { $sum: 1 }\n }\n}]\n[{\n $group: {\n _id: {\n year: { $year: \"$yourDateFieldName\" },\n month: { $month: \"$yourDateFieldName\" }\n },\n Total: { $sum: 1 }\n }\n}]\nyourDateFieldName$match$group"}, {"role": "user", "content": "Text:I think i have found the query.i managed to get 1 record per day and sun the values for 1 month, Thanks\nCode:[\n { \n $match: \n { \n \"fPort\": 60,\n \"rxInfo.time\":\n {\n \"$gte\": \"2020-12-01T00:00:00.000000Z\",\n \"$lte\": \"2020-12-31T59:59:59.99\" \n }\n } \n }, \n { \n $project:\n { \n _id:1,\n year:\n {\n $year: \n { \n $dateFromString: \n {\n dateString: \n {\"$arrayElemAt\": [ \"$rxInfo.time\", 0 ] }\n }\n }\n },\n month:\n {\n $month: \n {\n $dateFromString: \n { \n dateString: \n {\"$arrayElemAt\": [ \"$rxInfo.time\", 0 ] }\n }\n }\n },\n day:\n {\n $dayOfMonth: \n {\n $dateFromString: \n { \n dateString: \n {\"$arrayElemAt\": [ \"$rxInfo.time\", 0 ] }\n }\n }\n },\n sum : \"$object.TotalDaily\"\n } \n }, \n { \n $group: \n { \n _id:\n {\n year:\"$year\",\n month:\"$month\",\n day:\"$day\"\n },\n TotalPerDay:\n {\n $sum:\"$sum\"\n }\n }\n }, \n { \n $group: \n { \n _id: \"9cd9cb00000124c1\",\n \"MonthlyTotal\":\n {\n \"$sum\": \"$TotalPerDay\" \n },\n }\n }\n]"}, {"role": "user", "content": "Text:$object.TotalDailyHi @turivishal Thanks for the response,no i don\u2019t want count it, i want to add value of $object.TotalDaily together, but u only want to add 1 value per day, per month.I tried to use $group this way but i get a error.but keeps telling me \u201ccan\u2019t convert from BSON type array to Date\u201d.Thanks\nCode:$object.TotalDaily{\n _id: {\n year:{$year:\"$rxInfo.time\"},\n month:{$month:\"$rxInfo.time\"},\n day:{$dayOfMonth:\"$rxInfo.time\"}\n },\n \"Total\": \n {\n \"$sum\": \"$object.TotalDaily\"\n }\n}\n"}, {"role": "assistant", "content": "Text:The field \"$rxInfo.time\" having string type date and also inside an array, it should be date type and outside the array, you need to deconstruct the rxInfo array using $unwind, and than use $group stage.You have already did in your second reply, you can convert it using $dateFromString or $toDate Date Expression Operators, Before the $group stage inside $addFields, or inside the $group stage that you have already did.\nCode:\"$rxInfo.time\"rxInfo$group$group$addFields$group"}, {"role": "assistant", "content": "Text:Hi, I need to order all the data by months from an aggregate in a list recordsomething like thisJanuary01-01-2020filed1,field2,field302-01-2020fieild1,field2,field3February01-02-2020field1,field2,field302-02-2020field1,field2,field3April01-04-2020field1,field2,field302-04-2020field1,field2,field3And I have no clue how to do it.\nCode:"}, {"role": "assistant", "content": "Text:Hello @jack_austin, Welcome to the MongoDB community forum,This topic is not related to the current topic, Can you please ask your question in a new post?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Help with Mongo Realm and NextJS with User Authentication? and tags: ['node-js', 'app-services-user-auth', 'next-js', 'developer-hub']"}, {"role": "user", "content": "Text:Hello. I\u2019m new to Mongo, and Next JS.\nI read the article on How to Integrate MongoDB Into Your Next.js App today and now I\u2019m looking for more!I\u2019d like to build a NextJS app that uses Realm for user authentication with protected API routes for user data. Does anyone have a link to an tutorial article, or Github Repo or any other resources to do this?Looking forward to your responses.\nCode:"}, {"role": "assistant", "content": "Text:Hey Brian - While I don\u2019t think we have one, it seems like Vercel has an example of using Realm with Next.JS. Would this help? - Example with Monogdb ReamlWeb (#14555) \u00b7 vercel/next.js@1b5ca78 \u00b7 GitHub\nCode:"}, {"role": "user", "content": "Text:I will take a look when I can.\nCode:"}, {"role": "assistant", "content": "Text:Hey Brian,Depending on your approach to authentication, you\u2019d either use the Realm Web SDK or the Node.js SDK. But when it comes to Auth, are you trying to use Realm solely for auth or do you need other realm features in your app. The only reason I ask is that if you just need user authentication, a specific library like Next-Auth could be a better choice.\nCode:"}, {"role": "user", "content": "Text:I\u2019m planning to build a Admin/Dashboard app for authenticated users only. Non-authenticated users will only see a logon screen.I would love to use NextAuth if it supports Realm features. Other developers in my company are working with Realm for other, non-Next JS apps, so I think I need to find a way to tie into Realm for authentication.Does NextAuth work with Realm?\nCode:"}, {"role": "assistant", "content": "Text:Hey Brian - not sure what your implementation details are for auth in the other apps, but it seems like NextAuth would work with Realm if you use JWT Authentication. After using NextAuth to sign in, you can pass in the JWT that you get from the callback to Realm\u2019s JWT Auth provider\nCode:"}, {"role": "assistant", "content": "Text:How can assure I can call app.currentUser\nin the getServerSideProps ? It seems undefined if I call It on getServerSideProps\nCode:"}, {"role": "assistant", "content": "Text:Is there a concrete example for this? In the docs https://www.mongodb.com/docs/realm/web/nextjs/#log-the-user-in it saysIn a real application, you would want to have a more complex authentication flow. For more information, refer to the Next.js authentication documentation.Could anyone share of an example using Next Auth and Realm Web?\nCode:"}, {"role": "assistant", "content": "Text:I\u2019d also like to see a concrete example of a production-ready authentication flow.@Alexandar_Dimcevski did you manage to find a good example of figure out a good approach?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Getting Error while connecting to MongoDB using Node.js and tags: ['node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:I am getting this error, please help:\nCode: ServerDescription {\n address: 'localhost:27017',\n type: 'Unknown',\n hosts: [],\n passives: [],\n arbiters: [],\n tags: {},\n minWireVersion: 0,\n maxWireVersion: 0,\n roundTripTime: -1,\n lastUpdateTime: 27239058,\n lastWriteDate: 0,\n error: MongoNetworkError: connect ECONNREFUSED ::1:27017\n at connectionFailureError (C:\\AI\\ai-real-estate-friend\\node_modules\\mongodb\\lib\\cmap\\connect.js:383:20)\n at Socket. (C:\\AI\\ai-real-estate-friend\\node_modules\\mongodb\\lib\\cmap\\connect.js:307:22)\n at Object.onceWrapper (node:events:628:26)\n at Socket.emit (node:events:513:28)\n at emitErrorNT (node:internal/streams/destroy:151:8)\n at emitErrorCloseNT (node:internal/streams/destroy:116:3)\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {\n cause: Error: connect ECONNREFUSED ::1:27017\n at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {\n errno: -4078,\n code: 'ECONNREFUSED',\n syscall: 'connect',\n address: '::1',\n port: 27017\n },\n [Symbol(errorLabels)]: Set(1) { 'ResetPool' }\n },\n topologyVersion: null,\n setName: null,\n setVersion: null,\n electionId: null,\n logicalSessionTimeoutMinutes: null,\n primary: null,\n me: null,\n '$clusterTime': null\n }\n },\n stale: false,\n compatible: true,\n heartbeatFrequencyMS: 10000,\n localThresholdMS: 15,\n setName: null,\n maxElectionId: null,\n maxSetVersion: null,\n commonWireVersion: 0,\n logicalSessionTimeoutMinutes: null\n },\n code: undefined\n}\n"}, {"role": "assistant", "content": "Text:Hi @Musa_Mazhar,Welcome to the MongoDB Community forums It seems like MongoDB is not running or is not listening on port 27017.To troubleshoot this error, you can try:Let us know if you need any further help!Best,\nKushagra\nCode:"}, {"role": "user", "content": "Text:Hi Kushagra,Good day to you.Here\u2019s the snapshot from cmd window where it shows that MongoDB is running on port 27017. But somehow when I use the same cmd for Node.js, MongoDB gives above error.\n\nMongoDB1526\u00d7787 40.6 KB\n\nCode:"}, {"role": "assistant", "content": "Text:The::1:27017part in the error messageECONNREFUSED ::1:27017indicates that your localhost resolve to the IPv6 address rather than the IPv4 127.0.0.1. Try replacing localhost in your connection string with 127.0.0.1.\nCode:::1:27017ECONNREFUSED ::1:27017"}, {"role": "user", "content": "Text:Hi Steevej, so i replaced the localhost in connection string with 127.0.0.1. Here\u2019s the code for server.js file which I am trying to run in cmd using \u2018npm start\u2019\nCode:const express = require('express');\nconst mongoose = require('mongoose');\nconst cors = require('cors');\n\nconst app = express();\nconst PORT = process.env.PORT || 5000;\n\napp.use(cors());\napp.use(express.json());\n\nmongoose.connect('mongodb://localhost:127.0.0.1/ai-real-estate-friend');\n\nconst connection = mongoose.connection;\nconnection.once('open', () => {\n console.log('MongoDB database connection established successfully');\n});\n\napp.listen(PORT, () => {\n console.log(`Server is running on port: ${PORT}`);\n});\n\napp.get('/', (req, res) => {\n res.sendFile(path.join(__dirname, 'client/build', 'index.html'));\n});\n\nconst listingSchema = new mongoose.Schema({\n title: String,\n description: String,\n address: String,\n city: String,\n state: String,\n zip: String,\n price: Number,\n image: String\n});\n\nconst Listing = mongoose.model('Listing', listingSchema);\n\napp.get('/api', async (req, res) => {\n try {\n const listings = await Listing.find();\n res.json(listings);\n } catch (error) {\n console.error(error);\n res.status(500).send('Server error');\n }\n});\n"}, {"role": "assistant", "content": "Text:i replaced the localhost in connection string with 127.0.0.1You did not.You replaced the port 27017 with 127.0.0.1.mongoose.connect('mongodb://localhost:127.0.0.1/ai-real-estate-friend');\nCode:mongoose.connect('mongodb://localhost:127.0.0.1/ai-real-estate-friend');"}, {"role": "user", "content": "Text:Okay, maybe I am doing it wrong. Can you please guide me how to to replace the port?\nCode:"}, {"role": "user", "content": "Text:Thank you so much. I didn\u2019t correct it first, then I replaced it with. It worked. Thank you.\nCode:mongoose.connect('mongodb://127.0.0.1:27017/ai-realestate-friend');\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Connection to mongodb://127.0.0.1:27017 refused and tags: ['compass', 'mongodb-shell', 'server']"}, {"role": "user", "content": "Text:Hi,I believe that this question has been tackled here Connect ECONNREFUSED 127.0.0.1:27017 in Mongodb Compass but I am not entirely happy with it.I really closely follow the documentation https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/#installing-mongodb-6.0-edition-edition and https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/#run-mongodb-community-edition but in spite of that when I tryI obtain the deceptively optimistic messagewhile in fact running mongosh givesAlthough I do believe the solution exists, it is quite intimidating that it is not reflected in the docs. Currently, I am only able to run mongodb locally as a superuser\u2026\nCode:brew services start mongodb-community@6.0\n==> Successfully started `mongodb-community`\nmongoshmongosh\nCurrent Mongosh Log ID:\t63f0f50dc46c87b2ca8c78fc\nConnecting to:\t\tmongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.7.1\nMongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017\nmongodbsuperuser"}, {"role": "assistant", "content": "Text:I have the same problem\nCode:\u276f brew services start mongodb-community@6.0\n\n==> Successfully started `mongodb-community` (label: homebrew.mxcl.mongodb-community)\n\u276f mongosh\nCurrent Mongosh Log ID:\t63f2912b4d7d8dffb21c4f96\nConnecting to:\t\tmongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.7.1\nMongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017```"}, {"role": "assistant", "content": "Text:The error ECONNREFUSED means mongodb is not listening at the given address and port. The fact that mongodb has been started correctly does not mean that it listens to the given address and port.It is also possible that your firewall settings are preventing mongosh/Compass to connect.The configuration file will tell you which address and port are used by mongod.The commands ss or netstat can also be used to determine on which address/port mongod is listening.\nCode:"}, {"role": "user", "content": "Text:Thank you for your reply. So let\u2019s try to figure out what\u2019s going on here:Do I get it right that the problem could be in the fact that the port 27017 is not explicitly specified at the bindIp key?For the sake of completeness, I had a glimpse at the mongo.log file mentioned in the config, and this what happens when I try to run the mongosh command after starting the mongodb as a service:Is it helpful somehow? Thank you\nCode:/opt/homebrew/etc/mongod.confsystemLog:\n destination: file\n path: /opt/homebrew/var/log/mongodb/mongo.log\n logAppend: true\nstorage:\n dbPath: /opt/homebrew/var/mongodb\nnet:\n bindIp: 127.0.0.1, ::1\n ipv6: true\n27017bindIpmongo.logmongoshmongodb{\"t\":{\"$date\":\"2023-03-02T12:15:44.509+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20698, \"ctx\":\"-\",\"msg\":\"***** SERVER RESTARTED *****\"}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.514+01:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915701, \"ctx\":\"-\",\"msg\":\"Initialized wire specification\",\"attr\":{\"spec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"outgoing\":{\"minWireVersion\":6,\"maxWireVersion\":17},\"isInternalClient\":true}}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.518+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23285, \"ctx\":\"thread1\",\"msg\":\"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'\"}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.544+01:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4648602, \"ctx\":\"thread1\",\"msg\":\"Implicit TCP FastOpen in use.\"}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.549+01:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationDonorService\",\"namespace\":\"config.tenantMigrationDonors\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.549+01:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"namespace\":\"config.tenantMigrationRecipients\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.549+01:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"ShardSplitDonorService\",\"namespace\":\"config.tenantSplitDonors\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.549+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"thread1\",\"msg\":\"Multi threading initialized\"}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.550+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":69920,\"port\":27017,\"dbPath\":\"/opt/homebrew/var/mongodb\",\"architecture\":\"64-bit\",\"host\":\"Jiri-MacBook-Air-2.local\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.550+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23352, \"ctx\":\"initandlisten\",\"msg\":\"Unable to resolve sysctl {sysctlName} (number) \",\"attr\":{\"sysctlName\":\"hw.cpufrequency\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.550+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23351, \"ctx\":\"initandlisten\",\"msg\":\"{sysctlName} unavailable\",\"attr\":{\"sysctlName\":\"machdep.cpu.features\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.550+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"6.0.4\",\"gitVersion\":\"44ff59461c1353638a71e710f385a566bcd2f547\",\"modules\":[],\"allocator\":\"system\",\"environment\":{\"distarch\":\"aarch64\",\"target_arch\":\"aarch64\"}}}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.550+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Mac OS X\",\"version\":\"22.3.0\"}}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.550+01:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{\"config\":\"/opt/homebrew/etc/mongod.conf\",\"net\":{\"bindIp\":\"127.0.0.1, ::1\",\"ipv6\":true},\"storage\":{\"dbPath\":\"/opt/homebrew/var/mongodb\"},\"systemLog\":{\"destination\":\"file\",\"logAppend\":true,\"path\":\"/opt/homebrew/var/log/mongodb/mongo.log\"}}}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.552+01:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":5693100, \"ctx\":\"initandlisten\",\"msg\":\"Asio socket.set_option failed with std::system_error\",\"attr\":{\"note\":\"acceptor TCP fast open\",\"option\":{\"level\":6,\"name\":261,\"data\":\"00 04 00 00\"},\"error\":{\"what\":\"set_option: Invalid argument\",\"message\":\"Invalid argument\",\"category\":\"asio.system\",\"value\":22}}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.552+01:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":5693100, \"ctx\":\"initandlisten\",\"msg\":\"Asio socket.set_option failed with std::system_error\",\"attr\":{\"note\":\"acceptor TCP fast open\",\"option\":{\"level\":6,\"name\":261,\"data\":\"00 04 00 00\"},\"error\":{\"what\":\"set_option: Invalid argument\",\"message\":\"Invalid argument\",\"category\":\"asio.system\",\"value\":22}}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.553+01:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22270, \"ctx\":\"initandlisten\",\"msg\":\"Storage engine to use detected by data files\",\"attr\":{\"dbpath\":\"/opt/homebrew/var/mongodb\",\"storageEngine\":\"wiredTiger\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:44.553+01:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22315, \"ctx\":\"initandlisten\",\"msg\":\"Opening WiredTiger\",\"attr\":{\"config\":\"create,cache_size=7680M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.203+01:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1677755745:202842][69920:0x1f00cc140], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /opt/homebrew/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.204+01:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1677755745:204727][69920:0x1f00cc140], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /opt/homebrew/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.204+01:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1677755745:204945][69920:0x1f00cc140], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /opt/homebrew/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.204+01:00\"},\"s\":\"W\", \"c\":\"STORAGE\", \"id\":22347, \"ctx\":\"initandlisten\",\"msg\":\"Failed to start up WiredTiger under any compatibility version. This may be due to an unsupported upgrade or downgrade.\"}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.204+01:00\"},\"s\":\"F\", \"c\":\"STORAGE\", \"id\":28595, \"ctx\":\"initandlisten\",\"msg\":\"Terminating.\",\"attr\":{\"reason\":\"13: Permission denied\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.205+01:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23091, \"ctx\":\"initandlisten\",\"msg\":\"Fatal assertion\",\"attr\":{\"msgid\":28595,\"file\":\"src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp\",\"line\":708}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.205+01:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23092, \"ctx\":\"initandlisten\",\"msg\":\"\\n\\n***aborting after fassert() failure\\n\\n\"}\n"}, {"role": "assistant", "content": "Text:Is it helpful somehow?Very useful indeed.You have to fix the following file permission errors. I do not know how to do that on iOS.\nCode:{\"t\":{\"$date\":\"2023-03-02T12:15:45.203+01:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1677755745:202842][69920:0x1f00cc140], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /opt/homebrew/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.204+01:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1677755745:204727][69920:0x1f00cc140], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /opt/homebrew/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2023-03-02T12:15:45.204+01:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1677755745:204945][69920:0x1f00cc140], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /opt/homebrew/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n"}, {"role": "user", "content": "Text:@steevej You were right, I had to change the permission for WiredTiger.turtle and several other files. This state was probably a relict of the time when I started the process as superuser.Now I am a better mongodb user, thank you \nCode:WiredTiger.turtlesuperusermongodb"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Storing Images for E-Commerce Application and tags: ['data-modeling']"}, {"role": "user", "content": "Text:Ok\u2026 I\u2019m a newbe when it comes to MongoDB but I have a question that need a little more info on than just typing in a Google Search\u2026I am building a version of an E-Commerce platform\u2026 I need to allow store owners to upload images (max of 5) for a product image gallery\u2026My question is what is the best way to store them\u2026 My initial thought is to store them in their own database external to MongoDB and just link to the image through Embedded docs in the Product collection.Is this the best way\u2026 Or is there other options for me to look at?\nCode:"}, {"role": "assistant", "content": "Text:Hello @David_Thompson, take a look at this post with discussion and information about storing images in MongoDB database:\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Lookup & populate objects in array and tags: ['aggregation']"}, {"role": "user", "content": "Text:I have 2 collections (users and tenants). Simplified, the user looks like this:Simplified tenant model looks like this:And I\u2019d need to query a user with aggregated tenants, so ideally add a new field tenant next to the tenantId with the actual tenant document, like this:I know it can be done - it seems so simple, but I\u2019ve been banging my head agains the wall because of it So far I\u2019ve tried various combinations of $lookup, $project with $map, $mergeObject with $arrayElemAt, but nothing seems to cut it\u2026 The closest answer I cloud find was this: https://stackoverflow.com/questions/60342985, but I just don\u2019t seem to be able to adapt it. Can anyone see a way, please? Btw. (a bit unrelated) - if I $lookup the tenants and save them into a new field:The order of aggregatedAssociatedTenants is different than the order of associatedTenants. Doesn\u2019t $lookup preserve the order of the original array?\nCode:{\n \"_id\": ObjectId(\"...\"),\n \"associatedTenants\": [{\n \"tenantId\": ObjectId(\"A\"),\n \"role\": \"foo\"\n }, {\n \"tenantId\": ObjectId(\"B\"),\n \"role\": \"bar\"\n }]\n}\n{\n \"_id\": ObjectId(\"A\"),\n \"name\": \"Lorem\"\n}\ntenanttenantId{\n \"_id\": ObjectId(\"...\"),\n \"associatedTenants\": [{\n \"tenantId\": ObjectId(\"A\"),\n \"role\": \"foo\",\n \"tenant\": {\n \"name\": \"Lorem\"\n }\n }, {\n \"tenantId\": ObjectId(\"B\"),\n \"role\": \"bar\",\n \"tenant\": {\n \"name\": \"Ipsum\"\n }\n }]\n}\n$lookup$project$map$mergeObject$arrayElemAt$lookup$lookup: {\n from: \"tenants\",\n localField: \"associatedTenants.tenantId\",\n foreignField: \"_id\",\n as: \"aggregatedAssociatedTenants\"\n}\naggregatedAssociatedTenantsassociatedTenants$lookup"}, {"role": "assistant", "content": "Text:have you check the documentation? About half the page starts the examples.\n$lookup (aggregation) \u2014 MongoDB ManualIt would be better if you give 2-3 sample documents of each collection and your expected output from them. Replace all ObjectId with a number or simple string: {_id:123} or {_id:\"abc\"} (flexible types). Also add 1-2 more fields if you are not doing full merges. This will enable us to work on real (sample) data and find a solution faster.\nCode:{_id:123}{_id:\"abc\"}"}, {"role": "user", "content": "Text:Yes, I have seen all the examples on the $lookup stage Manual page. That\u2019s how got to try variations on $lookup + $replaceRoot + $mergeObjects + $arrayElemAt. Didn\u2019t help\u2026 (I wouldn\u2019t be asking if a haven\u2019t spent a good amount of time reading the docs, looking for answer and trying it on my own first.)Alright, both the user and tenant schemas are exactly as I have them in db and the desired result is also exactly as it should be, I just removed some unrelated fields and ObjectIds for better readability. I can repost it with actual ObjectIds:\nUser document:Tenant documents:Desired output:I\u2019ve added real ObjectIds. I\u2019ve also added some totally unrelated fields as well (although I don\u2019t see the point - as showcased in the original post, there\u2019s no merge, only adding a new field tenant with the full tenant document next to the tenantId - but in each item of array, that\u2019s the point I can\u2019t seem to get around).Thank you \nCode:$lookup$lookup$replaceRoot$mergeObjects$arrayElemAtusertenant{\n \"_id\": ObjectId(\"63732cb4919eee473ec5cec7\"),\n \"email\": \"user@domain.com\",\n \"associatedTenants\": [{\n \"tenantId\": ObjectId(\"636ad8dd185b079cf4cc3014\"),\n \"role\": \"foo\"\n }, {\n \"tenantId\": ObjectId(\"636a8ba3185b079cf4cc3012\"),\n \"role\": \"bar\"\n }]\n}\n[{\n \"_id\": ObjectId(\"636ad8dd185b079cf4cc3014\"),\n \"name\": \"Lorem\",\n \"domains\": [{ \"name\": \"lorem.example.com\" }]\n}, {\n \"_id\": ObjectId(\"636a8ba3185b079cf4cc3012\"),\n \"name\": \"Ipsum\",\n \"domains\": [{ \"name\": \"ipsum.example.com\" }]\n}]\n{\n \"_id\": ObjectId(\"63732cb4919eee473ec5cec7\"),\n \"email\": \"user@domain.com\",\n \"associatedTenants\": [{\n \"tenantId\": ObjectId(\"636ad8dd185b079cf4cc3014\"),\n \"role\": \"foo\",\n \"tenant\": {\n \"_id\": ObjectId(\"636ad8dd185b079cf4cc3014\"),\n \"name\": \"Lorem\",\n \"domains\": [{ \"name\": \"lorem.example.com\" }]\n }\n }, {\n \"tenantId\": ObjectId(\"636a8ba3185b079cf4cc3012\"),\n \"role\": \"bar\",\n \"tenant\": {\n \"_id\": ObjectId(\"636a8ba3185b079cf4cc3012\"),\n \"name\": \"Ipsum\",\n \"domains\": [{ \"name\": \"ipsum.example.com\" }]\n }\n }]\n}\ntenanttenanttenantId"}, {"role": "assistant", "content": "Text:We have users from all backgrounds and at all levels and we are not psychics, so please bear with us and do not expect anyone to know everything about you at first glance. especially, when you are new to a community, this is something unavoidable.and here is why I had those requests:The solution might come in a very simple form, but I can\u2019t promise I will be the one to deliver it. Also, if you tackle it yourself before we do, please share it with the rest of the community.PS: also in JSON format, it should be {\"$oid\":\"63732cb4919eee473ec5cec7\"} to be easily inserted into Atlas to test, for example.\nCode:{\"$oid\":\"63732cb4919eee473ec5cec7\"}"}, {"role": "assistant", "content": "Text:Ok, Took me a bit but here it is. As I said, your choice of words, especially \u201ctried everything\u201d confuses us about your level of understanding. So let me explain it so to improve you on what you might have missed on $lookup.And the tricky part is this:PS: a solution to a similar problem seems to exists here: mongodb - $lookup on ObjectId's in an array - Stack Overflow\nCode:[\n {\n \"$unwind\": {\n \"path\": \"$associatedTenants\"\n }\n },\n {\n \"$lookup\": {\n \"from\": \"tenant\",\n \"foreignField\": \"_id\",\n \"localField\": \"associatedTenants.tenantId\",\n \"let\": {\n \"tId\": \"$associatedTenants.tenantId\",\n \"tRole\": \"$associatedTenants.role\"\n },\n \"pipeline\": [\n {\n \"$project\": {\n \"_id\": 0,\n \"tenantId\": \"$_id\",\n \"role\": \"$$tRole\",\n \"tenant\": \"$$ROOT\"\n }\n }\n ],\n \"as\": \"associatedTenants\"\n }\n },\n {\n \"$unwind\": {\n \"path\": \"$associatedTenants\"\n }\n },\n {\n \"$group\": {\n \"_id\": \"$_id\",\n \"associatedTenants\": {\n \"$push\": \"$associatedTenants\"\n }\n }\n }\n]\n"}, {"role": "assistant", "content": "Text:Sorry for temporarily deleting my above post, if you were around at that time. It had a hiccup I failed to see.I corrected the problem and edited it. However, keep in mind the solution may not work if you change your field types too far from your example documents. if you will, then follow my explanation to adapt it to new situations or try searching the internet again with your now increased knowledge.\nCode:"}, {"role": "user", "content": "Text:You\u2019re amazing. Thank you! Especially for the explanation, that\u2019s more valuable as I prefer to understand it than just \u201cblindly\u201d solve it.And yeah, you\u2019re right (object ids, additional fields, everything), I\u2019m sorry if I sounded antagonistic or ungrateful\u2026 Thanks again for the help.\nCode:"}, {"role": "assistant", "content": "Text:Thanks, as long as we keep understanding of each other, we are cool By the way, I went ahead and asked on another topic if we can do it without $unwind. Though I am a bit lost in the answer, there is another approach you can try (you will need to adapt field names):See you around \nCode:"}, {"role": "assistant", "content": "Text:By the way, I went ahead and asked on another topic if we can do it without $unwind. Though I am a bit lost in the answer, there is another approach you can try (you will need to adapt field names):Similar approach but as per the expected result, you can also use $indexOfArray and $arrayElemAt instead of $filter and $first,Playground\nCode:$indexOfArray$arrayElemAt$filter$first$indexOfArraytenantId$arrayElemAtnamedb.users.aggregate([\n {\n \"$lookup\": {\n \"from\": \"tenants\",\n \"localField\": \"associatedTenants.tenantId\",\n \"foreignField\": \"_id\",\n \"as\": \"tenants\"\n }\n },\n {\n \"$addFields\": {\n \"associatedTenants\": {\n \"$map\": {\n \"input\": \"$associatedTenants\",\n \"in\": {\n \"$mergeObjects\": [\n \"$$this\",\n {\n \"tenant\": {\n \"name\": {\n \"$arrayElemAt\": [\n \"$tenants.name\",\n { \"$indexOfArray\": [\"$tenants._id\", \"$$this.tenantId\"] }\n ]\n }\n }\n }\n ]\n }\n }\n },\n \"tenants\": \"$$REMOVE\"\n }\n }\n])\n"}, {"role": "user", "content": "Text:Thanks guys!\nBoth solutions work quite nicely, but think I\u2019ll go with turivishal\u2019s approach as it\u2019s surprisingly simple (and requires slightly less tuning - the need to explicitly select tenant\u2019s fields is also nice as I was gonna $project it anyway).\nCode:"}, {"role": "assistant", "content": "Text:Hey,Thanks for the example. I\u2019m trying something similar, but I need the entire document, not the subset. So in this example, I would need the entire tenant document. I\u2019m just getting to grips with the aggregation pipeline and could do with some help.Appreciated,James\nCode:"}, {"role": "assistant", "content": "Text:I think this is pretty easy, actually. I just use arrayElemAt without the name prefix.\nCode:\"$arrayElemAt\": [\n \"$tenants.name\",\n { \"$indexOfArray\": [\"$tenants._id\", \"$this.tenantId\"] }\n ]\n"}, {"role": "assistant", "content": "Text:H @James_N_A2Here, we use \u201c$project\u201d in the pipeline of the \u201c$lookup\u201d to select fields. If you want the whole document, you can use just a \u201c$match\u201d stage instead, and use the \u201ctenantId\u201d we define by \u201clet\u201d before entering the pipeline.It is also possible without \u201clet\u201d and \u201cpipeline\u201d. check the usual examples for this way.In case you fail, then please open a new topic, give a minimal dataset to try and the expected result, along with what you tried so far, and also put a link to this post so others can see where else you looked.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Missin Realm Constructor error and tags: ['atlas-device-sync', 'react-native']"}, {"role": "user", "content": "Text:Hi, I perfectly followed the instructions that the documentation reported, but every time I start my app it gives me the Missing Realm Constructor error and I don\u2019t understand how to fix it, can you help me thanks. I use all the latest versions of React Native, Realm and Expo\nCode:"}, {"role": "assistant", "content": "Text:@Samuele_Cervietti This typically happens when the Realm .so is not linked into the compiled React Native project. Verify that pod install has indeed included Realm and do a rebuild of the project.Also I see you are using Expo. If you are attempting to use the web browser, then this error will also come up, as we are only compatible with Android and iOS.Can you provide a link to the documentation you are following? I can verify if something is missing.\nCode:.sopod installRealm"}, {"role": "user", "content": "Text:@Andrew_Meyer sorry but at the moment i am not home for work, as soon as i come back i will let you know, just one thing but i need to link my react native project with realm? It seemed to me that after version 0.65 it was no longer necessary\nCode:"}, {"role": "assistant", "content": "Text:You won\u2019t have to manually link anything. Did you follow our Expo documentation?This is based off of a template we created to help get started using Realm in React Native. Might be a good starting point to figuring out what is happening in your project.\nCode:"}, {"role": "user", "content": "Text:I had already created the project for some time, I just wanted to integrate Realm, can you advise me to create a new project and reinstall everything?\nCode:"}, {"role": "assistant", "content": "Text:It should work without creating a new project. But if you are using expo, you will need to use the expo-dev-client. This allows you to use 3rd party libraries in an Expo project. Here\u2019s the getting started documentation. Once you have that setup, you should be able to use Realm.\nCode:"}, {"role": "user", "content": "Text:Hi, I had already tried to use Expo-dev-client but without result, because when I launch the app through \u201cexpo start --dev-client\u201d it doesn\u2019t load the app when I try to open it with the expo app on play store\nCode:"}, {"role": "assistant", "content": "Text:Expo-dev-client is not compatible with Expo Go. You will have to build a dev client and install it on your device. Have you tried use the a simulator or emulator?\nCode:"}, {"role": "user", "content": "Text:I haven\u2019t tried any emulator yet, now I try, in case how do I create a development client? Excuse the many questions but it is the first time that such a thing has happened to me\nCode:"}, {"role": "user", "content": "Text:@Andrew_Meyer i tried with the emulator but it keeps giving me the same error ie that the realm constructor is missing. I followed the whole procedure but it didn\u2019t lead to anything, what can I do?\nCode:"}, {"role": "assistant", "content": "Text:It\u2019s hard to say without seeing the exact instructions you are using to install and run your project. I recommend trying out our expo-template and comparing the project contents to your project once you get that up and running. Maybe you will be able to find the issue through comparing a working realm project to yours.\nCode:"}, {"role": "user", "content": "Text:Okay, I saw that there is also the javascript version, is it okay if I try this? realm-js/templates/expo-template-js at master \u00b7 realm/realm-js \u00b7 GitHub\nCode:"}, {"role": "user", "content": "Text:I tried to install the Expo templates with realm, but both the typescript and JavaScript templates are not downloaded, when I run the script the download starts and stops almost immediately, creating just the folder, you know how I can\nCode:"}, {"role": "assistant", "content": "Text:Did you follow the instructions in the README?\nCode:"}, {"role": "user", "content": "Text:yes i read the documentation on README but it keeps giving me that problem\nCode:"}, {"role": "assistant", "content": "Text:What exact command do you type to produce this error?\nCode:"}, {"role": "user", "content": "Text:I tried to install both the typescript and JavaScript template, the commands I used, are these:Typescript:\nnpx create-react-native-app MyAwesomeRealmApp -t with-realmJavaScript:\nexpo init MyAwesomeRealmApp --template @realm/expo-template-js\nCode:"}, {"role": "assistant", "content": "Text:And this fails to download the template? Do other templates (non-realm) work?\nCode:"}, {"role": "user", "content": "Text:Executing the above commands does not download the realm model and gives me the error already mentioned, the other models work, also because I only use the default Expo templates (blank). And then I install the packages I need, I had done this for realm too before I knew it was giving an error\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Sudo systemctl start mongod not working and tags: []"}, {"role": "user", "content": "Text:Hello,I installed mongodb according to https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/ on ubuntu 20.04. I adhered the guide and did not change any configuration files or anything else. Now, when I run \u201csudo systemctl start mongod\u201d the terminal just executes the command but no output is produced. Running \u201csudo systemctl status mongod\u201d gives:Can somebody tell me what I have done wrong? Many thanks!\nCode:mongod.service - MongoDB Database Server\n Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)\n Active: failed (Result: exit-code) since Sun 2022-03-27 15:18:13 CEST; 19s ago\n Docs: https://docs.mongodb.org/manual\n Process: 54971 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=14)\n Main PID: 54971 (code=exited, status=14)\n"}, {"role": "assistant", "content": "Text:@peter_parker We may not be able to tell you what\u2019s wrong but the system logs should be able to tell you!cd /var/log and check the syslog and any mongo* logs.\nCode:cd /var/log"}, {"role": "user", "content": "Text:Thanks for your answer, it turns out that I had to change the write permission to the /var/lib/mongodb folder\nCode:"}, {"role": "assistant", "content": "Text:Excellent, have fun with MongoDB1\nCode:"}, {"role": "assistant", "content": "Text:\u250c\u2500\u2500(root\ud83d\udc80kali)-[/home/stark]\n\u2514\u2500# systemctl start mongod.service 3 \u2a2f\u250c\u2500\u2500(root\ud83d\udc80kali)-[/home/stark]\n\u2514\u2500# systemctl status mongod.service\n\u00d7 mongod.service - MongoDB Database Server\nLoaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)\nActive: failed (Result: signal) since Mon 2022-05-02 15:57:15 IST; 1s ago\nDocs: https://docs.mongodb.org/manual\nProcess: 2351 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=killed, signal=ILL)\nMain PID: 2351 (code=killed, signal=ILL)\nCPU: 17msMay 02 15:57:15 kali systemd[1]: Started MongoDB Database Server.\nMay 02 15:57:15 kali systemd[1]: mongod.service: Main process exited, code=killed, status=4/ILL\nMay 02 15:57:15 kali systemd[1]: mongod.service: Failed with result \u2018signal\u2019.\nCode:"}, {"role": "assistant", "content": "Text:please help me this error show my laptop when i put these command\ni used hp8440p laptopi5 i have linux os debian\nand i have win10 in my laptop here is work mongo but\nnot working in my linux os thro me this error please resolve this\nCode:"}, {"role": "assistant", "content": "Text:It terminated with SIGILL it means your CPU is INcompatible with the version of mongod you are trying to use.Search the forum with signal=ILL for potential solution.Thanks @Ramachandra_Tummala for the correction.\nCode:"}, {"role": "assistant", "content": "Text:steevej i think you meant incompatible\nCode:"}, {"role": "assistant", "content": "Text:I don\u2019t understand what want to say\nPlease answer me in docs type\nCode:"}, {"role": "assistant", "content": "Text:The CPU in your laptop is probably an i5-520M.\nThat CPU does not support the AVX instruction.\nTherefore, it will not run the latest versions of MongoDB.\nCode:"}, {"role": "assistant", "content": "Text:New here so be kind pls.Getting this error when trying to install Mongo 5 on Ubuntu release 20.04 LTS 64.\nmongod.service - MongoDB Database Server\nLoaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)\nActive: failed (Result: core-dump) since Fri 2023-02-17 22:23:04 EST; 31s ago\nDocs: https://docs.mongodb.org/manual\nProcess: 7221 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=dumped, signal=ILL)\nMain PID: 7221 (code=dumped, signal=ILL)Tried to uninstall and reinstall.Output from log:\nkernel: [ 3782.753092] traps: mongod[7221] trap invalid opcode ip:555b528a19da sp:7ffca788f9b0 error:0 in mongod[555b4e821000+51e5000]\nFeb 17 22:23:04 MobileMoe13 systemd[1]: mongod.service: Main process exited, code=dumped, status=4/ILL\nFeb 17 22:23:04 MobileMoe13 systemd[1]: mongod.service: Failed with result \u2018core-dump\u2019.\nFeb 17 22:25:57 MobileMoe13 PackageKit: daemon quitThanks in advanced.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Setting default values in data schema and tags: ['schema-validation']"}, {"role": "user", "content": "Text:Hello Enthusiast,\nI am implementing data schema. Here i have to mention default value to a field of document.is there any possible way to set default value to a field?Best Regards,\nM Jagadeesh.\nCode:db.createCollection(\"collect\", {\n validator: {\n $jsonSchema: {\n bsonType: \"object\",\n additionalProperties: true,\n required: [\"component\", \"path\"],\n properties: {\n component: {\n bsonType: \"string\"\n },\n path: {\n bsonType: \"string\",\n description: \"Set to default value\"\n }\n }\n }\n)\n"}, {"role": "assistant", "content": "Text:Hi @Manepalli_Jagadeesh,The schema validation is only intend to enforce/validate a schema definition and not populate values.The server does not have an ability to set default values and we recommend users to set it in their data access application layer or use ODM\u2019s to set those values on the application side.If you use Atlas you can consider having a trigger on the collection to update every inserted document with a specific filed value.Best regards,\nPavel\nCode:"}, {"role": "user", "content": "Text:Hi @Pavel_Duchovny,Thank you for information and providing hints to implement default values.Best Regards,\nM Jagadeesh.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: allowDiskUse setting in Compass and tags: ['aggregation', 'compass']"}, {"role": "user", "content": "Text:Hello.\nI\u2019m trying to build a view using Compass aggregation builder. I want to use $ group. Due to the size of the source collection, I need to add {allowDiskUse: true} to the aggregation pipeline. How and where can I set this parameter using Compass?\nThank you in advance for your help,\nRegards,\nMarek\nCode:"}, {"role": "assistant", "content": "Text:Hi @Marek_Bisztyga,Welcome to MongoDB community!Compass allows you to use a sample mode in the aggregation builder therefore you should be able to construct your pipeline in compass and use the \u201cexport\u201d button in the end.Only in 4.4 you can add the allowDiskUse is allowed in find.The {allowDiskUse: true} should be added to the query/aggregate command used on the already defined view therefore it cannot be done as part of the agg builder.Hope that helps.Best\nPavel\nCode:{allowDiskUse: true}"}, {"role": "user", "content": "Text:The {allowDiskUse: true} should be added to the query/aggregate command used on the already defined view therefore it cannot be done as part of the agg builder.Hi @Pavel_Duchovny\nTo add {allowDiskUse: true} to an already defined (through the aggregate command) view, I have to define the view first, and I cannot do this because to define it I have to add {allowDiskUse: true}.\nIs my reasoning correct?\nBest\nMarek\nCode:{allowDiskUse: true}"}, {"role": "assistant", "content": "Text:Hi @Marek_Bisztyga,Not necessarily. You can attempt the following:Create view with pipeline without the allowDiskUse, example:The view only consume the data when you query it. Here you can use the allowDiskUse:\nPrior 4.4 -From 4.4 you can use find:Thanks\nPavel\nCode: db.createView(\"myView\", \"myColl\" , [ { $group : {\"_id\" : \"$id\" , arr : { $push : \"$value\" }} }])\ndb.myView.aggregate([],{allowDiskUse : true });\n db.myView.find({},{},{allowDiskUse : true })\n"}, {"role": "user", "content": "Text:Hi Pavel.\nIt works.\nNow I have to figure out how to make the Tableau, which is supposed to see this view, work the same way.\nThanks for the help.\nBest,\nMarek\nCode:"}, {"role": "assistant", "content": "Text:Hi @Marek_Bisztyga,How do you connect to tableau? If its through the BI connector it always set allowDiskUse option on . So it should work:Best\nPavel\nCode:"}, {"role": "user", "content": "Text:Hi @Pavel_Duchovny\nOh! Great news!\nThank you.\nCode:"}, {"role": "assistant", "content": "Text:Hello,I have exactly the same issue, but I\u2019m afraid I still haven\u2019t managed to resolve it. When I try to use find with {},{},{allowDiskUse : true } on my view in Compass, I get the same error.Any chance you could help me out with this please?Thanks a lot,\nEmily\nCode:"}, {"role": "assistant", "content": "Text:Welcome to the MongoDB Community Forums @jamiesone!Please provide some more details on the issue you are encountering:Thanks,\nStennie\nCode:"}, {"role": "assistant", "content": "Text:Thank you for your reply!I have exactly the same issue as the other post in this thread. I\u2019m using the Compass aggregation builder to run a long pipeline including $group which previously worked, but now gives me the error\nCode:"}, {"role": "assistant", "content": "Text:ah sorry I can\u2019t work out how to edit my previous post\u2026It now gives me the error \u201cPlanExecutor error during aggregation :: caused by :: Exceeded memory limit for $group, but didn\u2019t allow external sort. Pass allowDiskUse:true to opt in.\u201dI tried filtering the view as you suggested,{},{},{allowDiskUse : true }But it gives me the same error.I\u2019m using Compass version 1.20.5 and the deployment is a MongoDB 5.0.2 Community on a kubernetes clusterThanks again,\nEmily\nCode:{},{},{allowDiskUse : true }"}, {"role": "assistant", "content": "Text:Hi @jamiesone ,\nI honestly don\u2019t recall how to pass that in compass.Can you build aggregation and run it with this setting in the shell tab?Thanks\nPavel\nCode:"}, {"role": "assistant", "content": "Text:Thanks for your reply! Yes, it definitely works in the shell once I\u2019ve added the allowDiskUse setting. But we\u2019d really like to find out how to enable this setting in Compass if possible as my colleague then runs a whole lot of other filters on the view, so it\u2019s really practical to be able to do this in Compass.Thanks again,\nEmily\nCode:"}, {"role": "assistant", "content": "Text:Hi @jamiesone ,Are you working with atlas? If yes what instances?Compass should add this by default\u2026\nCode:"}, {"role": "assistant", "content": "Text:Hello,No, I\u2019m not working with Atlas, I\u2019m using MongoDB 5.0.2 Community on a kubernetes cluster.It seems like the functionality was added at some point?\nhttps://jira.mongodb.org/browse/COMPASS-2722Thanks again for your help,\nEmily\nCode:"}, {"role": "assistant", "content": "Text:Hi Emily. I am having the exact same problem. I follow the instructions line by line but at the end of it I only get an empty view. How did you solve it?\nCode:"}, {"role": "assistant", "content": "Text:Hi Marek!Have you found a way to solve this?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Where is the password for the cluster? and tags: []"}, {"role": "user", "content": "Text:I can\u2019t find it anywhere in settings.\nThe UI for mongodb is the most confusing of anything I\u2019ve ever seen.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Alan_c, welcome to the community.\nYou can manage Atlas Users by clicking on the Database Access link in the sidebar under the security section.\n|625.1067961165048x2521022\u00d7412 45.4 KB\nAfter clicking on the link, you would see an interface like this:\n|624x187, 100%.00267276495391600\u00d7479 88.6 KB\n\nAlso, we have already discussed this question in our FAQ post, please take a look at question no. 6 for more information.In case you have any doubts, please feel free to reach out to us.Thanks and Regards.\nSourabh Bagrecha,\nCurriculum Services Engineer\nCode:"}, {"role": "assistant", "content": "Text:The password tho? Where exactly could it be retrieved?Regards,\nMarcelino\nCode:"}, {"role": "assistant", "content": "Text:You cannot retrieve the password\nIf you forgot the dbuser password edit the user and change the password as shown in the above snapshots\nor create a new user with add new database user link\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: com.mongodb.MongoSocketOpenException: Exception opening socket and tags: []"}, {"role": "user", "content": "Text:Hi All,Sometimes for one hour we are having connection issue in between Spring BootApplication 2.0.0 Release version with Mongo Db Java driver 3.11.1.\nApplication is deployed in Azure App service.It works good but some of the requests are getting below issue.Please let me know if anyone have similar issue.\nCode:com.mongodb.MongoSocketOpenException: Exception opening socket\n\tat com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-3.11.1.jar!/:na]\n\tat com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128) ~[mongodb-driver-core-3.11.1.jar!/:na]\n\tat com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.11.1.jar!/:na]\n\tat java.base/java.lang.Thread.run(Unknown Source) ~[na:na]\nCaused by: java.net.SocketTimeoutException: connect timed out\n\tat java.base/java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:na]\n\tat java.base/java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) ~[na:na]\n\tat java.base/java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) ~[na:na]\n\tat java.base/java.net.AbstractPlainSocketImpl.connect(Unknown Source) ~[na:na]\n\tat java.base/java.net.SocksSocketImpl.connect(Unknown Source) ~[na:na]\n\tat java.base/java.net.Socket.connect(Unknown Source) ~[na:na]\n\tat java.base/sun.security.ssl.SSLSocketImpl.connect(Unknown Source) ~[na:na]\n\tat com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:64) ~[mongodb-driver-core-3.11.1.jar!/:na]\n\tat com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-3.11.1.jar!/:na]\n\tat com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-3.11.1.jar!/:na].\n"}, {"role": "assistant", "content": "Text:Hi @vamsi_krishna welcome to the community!It seems that the error was a connection time out from the java.net side and not from the MongoDB driver particularly. I\u2019m not sure why this is so, since the reason may be specific to Azure App Service.Do you see a similar issue when not using the App Service? Also, it could be a limitation of certain pricing tier. Have you tried using a higher tier and see a similar failure?Best regards,\nKevin\nCode:java.net"}, {"role": "user", "content": "Text:@Kevin.\nThank you for responding to my query.\nYes, we are seeing this issue in Azure APP service. It is working good in local system.\nRegarding app service plans. Sure, will check that one.Thank you.\nCode:"}, {"role": "user", "content": "Text:@kevinadiWe are using Production P2V2 App Service Plan in Azure.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Intermediate MongoTimeoutError: Server selection timed out after 30000 ms and tags: ['node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:We are seeing intermediate issue of pod crashing with error stating MongoTimeoutError: Server selection timed out after 30000 ms when it is trying to connect mongoDb. On replacing the pod it is able to connect successfully. If we again try to replace the running pod we see above error. It is intermediate, could anyone help us here. Mongoose version used is 5.8\nCode:"}, {"role": "assistant", "content": "Text:When you say pod are you referring to K8s?\nCode:"}, {"role": "user", "content": "Text:yes @Andrew_Davidson\nCode:"}, {"role": "user", "content": "Text:We have whitelist of all ip via 0.0.0.0 is in place and we use a m30 clusterBelow is the code snippet which we are using to connect mongo atlasmongoose version: \u201cmongoose\u201d: \u201c5.8.7\u201d\nmongo: 4.2.21<<<<< code >>>>>var options = {\nuseNewUrlParser: true,\nuseUnifiedTopology: true,\nuseFindAndModify:false,\nconnectTimeoutMS: 300000,\nsocketTimeoutMS:0 ,\nkeepAlive: 1\n};mongoose.connect(\u201cconnection string\u201d, options, function (err) {\nif (err) {\nlogger.critical(\"Error while connecting to mongoDB \u2026 \", err);\n} else {\nlogger.info(\u201cmongodb connected successfully.\u201d)\n}\n});\nCode:let db = mongoose.connection;\ndb.once('open', function () {\n logger.info('MongoDB event open');\n db.on('connected', function () {\n logger.info('MongoDB event connected');\n });\n\n db.on('error', function (err) {\n logger.info('MongoDB event error.: ' + err);\n });\n});\n"}, {"role": "user", "content": "Text:Tested above code with mongoose version 6.5.x with the above code snippetvar options = {\u201cssl\u201d:true,\u201csslValidate\u201d:false,\u201cuseNewUrlParser\u201d:true,\u201cuseUnifiedTopology\u201d:false,\u201ckeepAlive\u201d:1,\u201cconnectTimeoutMS\u201d:300000,\u201csocketTimeoutMS\u201d:0}Error while connecting to mongoDB \u2026 may be down Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you\u2019re trying to access the database from an IP that isn\u2019t whitelisted. Make sure your current IP address is on your Atlas cluster\u2019s IP whitelist: https://docs.atlas.mongodb.com/security-whitelistMongoDB event error.: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you\u2019re trying to access the database from an IP that isn\u2019t whitelisted. Make sure your current IP address is on your Atlas cluster\u2019s IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/Basically with both version 5.8 and 6.5 we are facing similar issue just that error message are different , could any one help us here who has faced these issues\nCode:"}, {"role": "assistant", "content": "Text:It\u2019s not going to be any kind of configuration if it\u2019s intermittent like this.Are there any other suspicious events in the time before it crashes? Have you check the logs for the pod?\nCode:"}, {"role": "user", "content": "Text:@Dan_Mckean we don\u2019t see any suspicious things , we are only seeing below error in the log\n\nScreenshot 2022-08-01 at 2.08.20 PM3584\u00d7188 38.7 KB\n\n\nScreenshot 2022-07-29 at 7.41.05 PM3158\u00d7152 34.1 KB\nError while connecting to mongoDB\nmay\nbe down Could not connect to any servers in your MongoDB Atlas cluster.\nOne common reason is that you\u2019re trying\nto\nfrom an IP that isn\u2019t whitelisted. Make sure vour current IP address is on vour Atlas cluster\u2019s IP whitelist: httos://docs.atlas.monaodb.com/securitv-whiteli\n14:05:26.446Z] [INFO]: [BPA] [cisco-bpa-platform/mw-backup-restorel [ServerName: bpa-ns] [PodName: backup-restore-service-5fb4d8f4dc-bm9vv] [session-id: 1 [c\n10DB event error.: MonaooseserverselectionError: Could not connect to anv servers in vour MonaoDB Atlas cluster. One common reasonWe try to open multiple concurrent connections is that any concerns here ?\nCode:"}, {"role": "assistant", "content": "Text:We try to open multiple concurrent connections is that any concerns here ?I think it probably depends on how many multiple is\u2026! I\u2019m not sure of the limits but I\u2019m sure it\u2019s fine for sensible numbers.My suggestion would be to open a support case (top right in Atlas) and see if our support folks can help take a look at things from the Atlas end of things. Perhaps we have some logs on that end.\nCode:"}, {"role": "user", "content": "Text:@Dan_Mckean @Andrew_DavidsonOn further investigations below are the observationsSince this issue is reproducible all over the time, we tried packet capture between working pod and non working pod [both of same deployment version], the observation here is in the non working scenario, after the client makes TCP connection it tries to perform TLS client hello but the pod is not getting reply from the mongodb server resulting in timeout and repeated retries. In all retries the TLS client hello is sent but mongodb server is not replying back.We further did a deep dive analysis on the packet capture and found that, when the client is making \u201cClient Hello\u201d, for working pods its taking TLSv1.2 protocol and in a non working its using TLSv1 protocol layer\u2026It is very intermediate, application fails to get connection with TLS1.0 , but with TLS1.2 is able to connect successfullyIn mongo db atlas we have set TLS 1.0 and above , still the pod crashes when at run time TLS1.0 gets used.Could someone help us here , we are clueless how to go ahead\nCode:"}, {"role": "assistant", "content": "Text:Good find Is there any possibility of configuring your application to consistently use TLS1.2? That would be the ideal for security reasons.And did you enable it by editing the deployment configuration and changing it as follows?\n\nimage855\u00d7307 44.3 KB\nBut yes, in theory Atlas can still support TLS1.0 - if that\u2019s been enabled in the cluster settings (as above) but it\u2019s not being accepted for those incoming connections I\u2019d suggest opening a support case (top right in Atlas) and see if our support folks can help take a look at things from the Atlas end of things.\nCode:"}, {"role": "user", "content": "Text:@Dan_Mckeanyes we have enabled deployment configuration from day 1 here is screen shot for the same\n\nimage1756\u00d7560 76 KB\nIn that scenario it should work right with TLS1.0, and from the application we are not setting TLS version, could be mongoose driver [5.8.7] thats using it at runtime. Is there a way we could set TLS version when we try to connect via mongoose?Below is the TCP dump for working pod\n\nimage1508\u00d7478 92.6 KB\nBelow is the TCP dump for non working pod\n\nimage1246\u00d7447 50.5 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Sorry - we\u2019ve reached the limits of my ability to help in this area.Are you able to open a support case so that someone can help diagnose why TLS1.0 isn\u2019t working as it should?\nCode:"}, {"role": "user", "content": "Text:@MaBeuLux88 could you help us here, we are currently clueless\nIn addition to above issue mentioned we see in logsmongoose connect(\u2026) failed with err: MongoNetworkError: failed to connect to server [hostname:27017] on first connect [Error: read ETIMEDOUT\nat TLSWrap.onStreamRead (internal/stream_base_commons.js:209:20)\nat TLSWrap.callbackTrampoline (internal/async_hooks.js:130:17) {\nname: \u2018MongoNetworkError\u2019,\n[Symbol(mongoErrorContextSymbol)]: {}\n}]\nat Pool. (/home/node/app/node_modules/mongodb/lib/core/topologies/server.js:433:11)\nat Pool.emit (events.js:400:28)\nat /home/node/app/node_modules/mongodb/lib/core/connection/pool.js:577:14\nat /home/node/app/node_modules/mongodb/lib/core/connection/pool.js:1021:9Clearly says its a TLS issue , can some one help us here\nCode:"}, {"role": "assistant", "content": "Text:Hey all,I read the thread in diagonal but looks like you two have been pretty far in the debugging already. I\u2019d try to use the latest versions (both for Mongoose and MDB) to see if that solves the problem. I\u2019d also try to update & upgrade the OS (linux?) running the pods and make sure they are using the latest libssl package or equivalent.Else open a ticket because it could also be a weird bug that needs proper investigation from the Atlas team.Cheers,\nMaxime.\nCode:"}, {"role": "user", "content": "Text:Hey @MaBeuLux88In addition to above issue we noticed below error , noting hostname of one of the primary is getting printed with error MongoNetworkError. Could you please look into these logsWe have also raised case, its been 48 hrs no help from the support team\nCode:[2022-08-05T15:37:59.091Z] [INFO]: [] [platform/activation] [ServerName: ns] [PodName: 7cbb8b8c69-rp9wn] [session-id: ] [correlation-id: ] MongoDB event error.: MongoNetworkError: failed to connect to server [secondaryHostname:27017] on first connect [MongoNetworkError: connection 5 to <>:27017 timed out\n at TLSSocket. (/home/node/app/node_modules/@platform/common-app/node_modules/mongodb/lib/core/connection/connection.js:355:7)\n at Object.onceWrapper (events.js:519:28)\n at TLSSocket.emit (events.js:400:28)\n at TLSSocket.Socket._onTimeout (net.js:495:8)\n at listOnTimeout (internal/timers.js:557:17)\n at processTimers (internal/timers.js:500:7) {\n [Symbol(mongoErrorContextSymbol)]: {}\n}]\n\n\n[2022-08-05T15:37:59.208Z] [INFO]: [] [platform/activation] [ServerName: ns] [PodName: -7cbb8b8c69-rp9wn] [session-id: ] [correlation-id: ] MongoDB event error.: MongoNetworkError: failed to connect to server [< (/home/node/app/node_modules/@-platform/-common-app/node_modules/mongodb/lib/core/connection/connection.js:355:7)\n at Object.onceWrapper (events.js:519:28)\n at TLSSocket.emit (events.js:400:28)\n at TLSSocket.Socket._onTimeout (net.js:495:8)\n at listOnTimeout (internal/timers.js:557:17)\n at processTimers (internal/timers.js:500:7) {\n [Symbol(mongoErrorContextSymbol)]: {}\n}]\n\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: mongod.service Failed with result core-dump and tags: []"}, {"role": "user", "content": "Text:Hi Mongodb OPS and Sysad,I\u2019m new to mongodb and currently working on a virtual machine installed with redhat. it happens that we tried to change the permission of the following while adding the keyfile on the security option under /etc/mongod.confthen we restart the mongodb using the command systemctl restart mongodhere\u2019s the error:\u25cf mongod.service - MongoDB Database Server\nLoaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor pres>\nActive: failed (Result: core-dump) since Wed 2021-02-24 13:41:34 PST; 1 day >\nDocs: https://docs.mongodb.org/manual\nProcess: 1279 ExecStart=/usr/bin/mongod $OPTIONS (code=dumped, signal=ABRT)\nProcess: 1277 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited,>\nProcess: 1274 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (cod>\nProcess: 1271 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, s>mongod[1279]: mongod(_ZN5mongo11Initial>\nmongod[1279]: mongod(_ZN5mongo21runGlob>\nmongod[1279]: mongod(+0xD9DF2A) [0x560b>\nmongod[1279]: mongod(+0xD1F719) [0x560b>\nmongod[1279]: libc.so.6(__libc_start_ma>\nmongod[1279]: mongod(_start+0x2E) [0x56>\nmongod[1279]: ----- END BACKTRACE -----\nsystemd[1]: mongod.service: Control proc>\nsystemd[1]: mongod.service: Failed with >\nsystemd[1]: Failed to start MongoDB Data>I tried to uninstall using this command below:sudo service mongod stop\nsudo apt-get purge mongodb-org*Remove Data Directories.\nRemove MongoDB databases and log files.sudo rm -r /var/log/mongodb\nsudo rm -r /var/lib/mongodbAnd fresh install mongodb to another version same thing happened error message didn\u2019t disappeared and mongodb service failed to start.Mongodb Current Version: MongoDB shell version v4.2.8\nOS: Red Hat Enterprise Linux release 8.2 (Ootpa)Hoping from this forum someone can help me on this issue and able to share some ideas to fix it. Thank you in advance.\nCode:"}, {"role": "assistant", "content": "Text:@Ian_Sherwin_Canaya Do you get the solution for this issue ? I have also this issue i can\u2019t get solution yet\u2026if you get the solution please give the method\u2026\nCode:"}, {"role": "assistant", "content": "Text:Hi @Ian_Sherwin_Canaya and @ajay_ps, even I\u2019m new to MongoDB and I too had this error or whatever we can call this. I searched a ton of communities and was unable to find a fix and at the end came to a decision of reinstalling MongoDB from scratch by first removing all the packages and directories like log, database etc. After reinstalling it works fine.About the error:\nI have encountered two types of similar errors so far. One is similar to the one talked about in this post Active: failed (Result: core-dump) for which only fix I could find was to reinstall from scratch. I read somewhere that this is a possible consequence of crashed or corrupted database which can be caused by terminating the database in a way which shouldn\u2019t be used ( I have no idea what way is it).Another similar error is Active: failed (Result: exit-code). This can be caused by various correctable reasons like ownership (chown) or rwx (chmod) permissions of the log file and dbpath, the mongod service not running, etc.I hope someone would find this information useful \nCode:Active: failed (Result: core-dump)Active: failed (Result: exit-code)"}, {"role": "assistant", "content": "Text:@Yashvander_Bamel I reinstalled many times after deleting all packages. But No solution. and i changed the user in ubuntu and again installed but no solutions.\nChecking time \u201csudo systemsctl start mongod\u201d and after \u201cmongo\u201d command then get the error. Illegal instruction (core dumped)\u2026 this is the main issue\nI can\u2019t get any solution yet\u2026\nCode:"}, {"role": "assistant", "content": "Text:Did mongodb work on your system even once? Did you get this error when you installed mongodb for the first time ever? If that\u2019s the case I can not comment anything.But if it did run once and then crashed, you can remove all the packages and use steps mentioned here and delete all the files associated with mongodb. And then try to reinstall. Note that this would work only if you could run mongodb atleast once on your system as far as I can tell. But you can try in the other case as well.And once you reinstall mongodb again, do not forget to change the ownership and permissions of the log and data folders\nCode:"}, {"role": "assistant", "content": "Text:Found this on StackOverflow, very underrated answer. The KVM processor used in most Linux VM environments is NOT COMPATIBLE with MongoDB, try to change it to something else. I use Proxmox, and when I changed from KVM processors to EPYC it worked right away, no changes.\nCode:"}, {"role": "assistant", "content": "Text:how do you change it? can you tell me?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: I cannot MongoDB on Ubuntu 22.04 LTS and tags: []"}, {"role": "user", "content": "Text:Greetings.I want to install mongoDB but I cannot. I tried it at Oracle cloud, Ubuntu 22.04 LTS. I tried to follow this, but error occurs in last command(sudo apt install mongodb-org).\n\n\uc2a4\ud06c\ub9b0\uc0f7 2022-08-16 14-35-17866\u00d7614 109 KB\n\nI tried to sudo apt install libcurl1.1, but it occurs Error: E: Package \u2018libssl1.1\u2019 has no installation candidate.How can I install MongoDB in Ubuntu 22.04 LTS? I cannot downgrade my instance\u2019s OS.\nCode:"}, {"role": "user", "content": "Text:PS. I founded \u2018E: Unable to correct problems, you have held broken packages.\u2019 and why this error occurs.I tried to sudo apt install libcurl1.1, but it occurs Error: E: Package \u2018libssl1.1\u2019 has no installation candidate.this is that\u2019s solution.\nCode:"}, {"role": "assistant", "content": "Text:Check this link\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: DeprecationWarning: Mongoose: the `strictQuery` and tags: ['node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:hi\ni am reciving thiss error while i try to connect to mongo db using mongooseBlockquote\n(node:20404) [MONGOOSE] DeprecationWarning: Mongoose: the strictQuery option will be switched back to false by default in Mongoose 7. Use mongoose.set('strictQuery', false); if you want to prepare for this change. Or use mongoose.set('strictQuery', true); to suppress this warning.i need to know what are the strictQuery and why i am getting this error\nCode:strictQueryfalsemongoose.set('strictQuery', false);mongoose.set('strictQuery', true);"}, {"role": "assistant", "content": "Text:Hello @mina_remon ,Welcome to The MongoDB Community Forums! Schemas have a few configurable options which can be passed to the constructor or to the set method:When strict option is set to true , Mongoose will ensure that only the fields that are specified in your Schema will be saved in the database, and all other fields will not be saved (if some other fields are sent). In simple term, the strict option, ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db. Mongoose supports a separate strictQuery option to avoid strict mode for query filters. This is because empty query filters cause Mongoose to return all documents in the model, which can cause issues.To learn more about these options, please go through Mongoose v6.9.0: Schemas.Regards,\nTarun\nCode:setnew Schema({..}, options);\n\n// or\n\nconst schema = new Schema({..});\nschema.set(option, value);\nstrictstrictQuery"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Realm schema for different object types in array and tags: ['graphql']"}, {"role": "user", "content": "Text:HiEDIT: For clarity I have explained this as different object types in array instead of multiple types per field.NOTE: In the case of different scalar types in the same field there is an outstanding issue with GraphQL (not Realm GraphQL) to have this supported in GraphQL schemas see Additional Note 1 below.Environment:MongoDB Atlas cluster running MongoDB 4.4\nMongoDB Realm connected to clusterIssue:I am trying to configure a Realm schema and Realm GraphQL (and later Sync) to support data where an array of objects can contain different objects, regardless of what I try I am unable to generate/create a valid schema that reflects the data and also works for Realm GraphQL.I am investigating and asking for help in case anyone else has a solution or potential solution that could be implemented in Realm GraphQL.What I am trying to achieve:The problem:Here is a simplified sample of the data I am trying to model, specifically the \u201cresults\u201d array should be capable of accepting different \u201cresult\u201d objects, and ideally each \u201cresult\u201d object should be unique with respect to \u201ctype\u201d. (see Additional Note 2 below for alternate data structure)What I have tried so far:1 - I have inserted the typed data into a MongoDB collection:\ndata1390\u00d7560 61.2 KB\n2 - I have written a MongoDB collection validation using json schema which validates the data, note the use of an array of bsonType for \u201cvalue\u201d:The following MongoDB collection validation also validates, note the use of anyOf to validate each \u201cresults\u201d item:3 - I then use Realm to generate a schema from the data (Realm \u2192 Schema \u2192 select collection \u2192 Schema tab \u2192 Generate Schema), Realm suggests the following schema - note that the bsonType suggested is the first type in the array - in this case int, but if a different type was first in the array the generator would suggest that but not multiple types.\nNOTE: you can set the bsonType to string which will allow a Realm GraphQL query to return the data as strings but not the type, this also means that mutations are not strongly typed and do not accept int or double values as desired.4 - This schema is accepted by Realm GraphQL (no warnings) but when a query is run the results are not correct - note that the string value is returned as null and the double value has been truncated:GraphQL query run in GraphiQL:Result:5 - If I try to modify the Realm schema to match the data using an array of bsonTypes as suggested by the Realm documentation specifically in the note:The fields available in a JSON schema object depends on the type of value that the schema defines. See the document schema types reference page for details on all of the available schema types.that links to this documentation and shows \u201cThe following fields are available for all schema types\u201d should accept an array for bsonType:The Realm schema should become:however this Realm schema causes Realm GraphQL to show a warning:results.value\tInvalidType\terror processing \u201ctype\u201d property in JSON Schemaand trying to run a query returns an error:GraphQL query run in GraphiQL:Result (error):6 - I have also tried generating a valid JSON Schema using online tools and by manually constructing a schema, in these cases the tools sometimes suggest the use of \u201canyOf\u201d however in each instance even if the schema is accepted by Realm it still shows the same GraphQL Schema generation warning.Latest / TLDR:Based on my investigation and the information about GraphQL union types described in the GraphQL GitHub issues it should be possible to use a union type in the Realm GraphQL schema to handle different objects nested in arrays.In the GraphQL schema:However I cannot see any way to customise the Realm GraphQL schema - there is an open issue to allow custom Realm GraphQL schema - please vote for this:Dear MongoDb GraphQl Stitch developers,\n\nIs it possible to add an ability to modify the final GraphQl schema (in order to remove unnecessary for my API stuff)\nOR\nBuild it based on existed roles?\n\nFor example, Im building a \"read only\" GraphQl API and...\n.\n.Additional:Additional Note 1:I have found there is a GraphQL proposal to support multiple scalar types in fields, for example using a string or double for the same field: Proposal: Support union scalar types #215This is so that for the data:you could specify a GraphQL schema:Currently it seems a workaround is to define a \u2018union\u2019 type in GraphQL and then use that union type rather than scalar types:For example in GraphQL:Additional Note 2:If possible each \u201cresult\u201d object should contain similar field names, however if this causes problems\nthe data could be modelled with each object having different field names, for example:\nCode:{\n \"name\": \"This is a text string\",\n \"results\": [\n { \"type\": \"count\", \"value\": 12, \"unit\": \"items\" },\n { \"type\": \"comment\", \"value\": \"A text comment\", \"unit\": \"n/a\" },\n { \"type\": \"weight\", \"value\": 56.69, \"unit\": \"kg\" }\n ]\n}\n{\n $jsonSchema: {\n bsonType: \"object\",\n properties: {\n _id: { bsonType: \"objectId\" },\n name: { bsonType: \"string\" },\n results: {\n bsonType: \"array\",\n items: {\n bsonType: \"object\",\n properties: {\n type: { bsonType: \"string\" },\n value: { bsonType: [ \"string\" , \"int\", \"double\" ] },\n unit: { bsonType: \"string\" }\n }\n }\n }\n }\n }\n}\n{\n $jsonSchema: {\n bsonType: \"object\",\n properties: {\n _id: { bsonType: \"objectId\" },\n name: { bsonType: \"string\" },\n results: {\n bsonType: \"array\",\n items: {\n anyOf: [\n {\n bsonType: \"object\",\n properties: { type: { bsonType: \"string\" }, value: { bsonType: \"string\" }, unit: { bsonType: \"string\" } }\n },\n {\n bsonType: \"object\",\n properties: { type: { bsonType: \"string\" }, value: { bsonType: \"int\" }, unit: { bsonType: \"string\" } }\n },\n {\n bsonType: \"object\",\n properties: { type: { bsonType: \"string\" }, value: { bsonType: \"double\" }, unit: { bsonType: \"string\" } }\n }\n ]\n }\n }\n }\n }\n}\n{\n \"title\": \"example\",\n \"properties\": {\n \"_id\": { \"bsonType\": \"objectId\" },\n \"name\": { \"bsonType\": \"string\" },\n \"results\": {\n \"bsonType\": \"array\",\n \"items\": {\n \"bsonType\": \"object\",\n \"properties\": {\n \"type\": { \"bsonType\": \"string\" },\n \"unit\": { \"bsonType\": \"string\" },\n \"value\": { \"bsonType\": \"int\" }\n }\n }\n }\n }\n}\nquery { example { _id name results { type unit value } } }\n{\n \"data\": {\n \"example\": {\n \"_id\": \"60755d9c0000b6ffe15cf906\",\n \"name\": \"This is a text string\",\n \"results\": [\n { \"type\": \"count\", \"unit\": \"items\", \"value\": 12 },\n { \"type\": \"comment\", \"unit\": \"n/a\", \"value\": null },\n { \"type\": \"weight\", \"unit\": \"kg\", \"value\": 56 }\n ]\n }\n }\n}\n ...\n \"bsonType\": \"\" | [\"\", ...],\n ...\n{\n \"title\": \"example\",\n \"properties\": {\n \"_id\": { \"bsonType\": \"objectId\" },\n \"name\": { \"bsonType\": \"string\" },\n \"results\": {\n \"bsonType\": \"array\",\n \"items\": {\n \"bsonType\": \"object\",\n \"properties\": {\n \"type\": { \"bsonType\": \"string\" },\n \"unit\": { \"bsonType\": \"string\" },\n \"value\": { \"bsonType\": [ \"string\", \"int\", \"double\" ] }\n }\n }\n }\n }\n}\nquery { example { _id name results { type unit value } } }\n{\n \"data\": null,\n \"errors\": [\n {\n \"message\": \"Cannot query field \\\"value\\\" on type \\\"ExampleResult\\\".\",\n ...\n }\n ]\n}\ntype CustomTypeComment { type: String, value: String, unit: String }\ntype CustomTypeCount { type: String, value: Int, unit: String }\ntype CustomTypeWeight { type: String, value: Double, unit: String }\nunion CustomResultType = CustomTypeComment | CustomTypeCount | CustomTypeWeight\n\ntype Event { id: String!, name: String, results: [CustomResultType] }\n[\n { \"_id\": \"...\", \"multi\": \"A string\" },\n { \"_id\": \"...\", \"multi\": 10.25 },\n]\n...\nfield: Int | String\n...\ntype CustomTypeOne { id: Int, value: String }\ntype CustomTypeTwo { id: Int, value: Int }\nunion CustomType = CustomTypeOne | CustomTypeTwo\n\ntype Event { id: Int!, results: [CustomType] }\n{\n \"name\": \"This is a text string\",\n \"results\": [\n { \"type\": \"count\", \"count\": 12, \"unit\": \"items\" },\n { \"type\": \"comment\", \"comment\": \"A text comment\" },\n { \"type\": \"time\", \"time\": 5600, \"unit\": \"s\" }\n ]\n}\n"}, {"role": "assistant", "content": "Text:Did you found any solution for this ? I am also facing the same issue with Realm.\nCode:"}, {"role": "user", "content": "Text:Edit - details moved to original post.\nCode:"}, {"role": "assistant", "content": "Text:We don\u2019t currently support a union of scalar types in our default GraphQL service to stay as close to the spec as possible. That being said, there is a workaround to achieve something similar by setting the schema of the field like so:{ \"field\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] } }The generated schema will ignore this field, but it can still be accessed via the custom resolver, (likely by having to define two different types).\nCode:{ \"field\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] } }"}, {"role": "user", "content": "Text:Hi SumedhaI tried using anyOf in my Realm schema you suggested:As expected the Realm GraphQL still gives me a schema error and ignores the field:Can you explain how I can access the collection using a custom resolver / define two different types\nCode:{\n \"title\": \"example\",\n \"properties\": {\n \"_id\": { \"bsonType\": \"objectId\" },\n \"name\": { \"bsonType\": \"string\" },\n \"results\": {\n \"bsonType\": \"array\",\n \"items\": {\n \"bsonType\": \"object\",\n \"properties\": {\n \"type\": { \"bsonType\": \"string\" },\n \"value\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" } ] },\n \"unit\": { \"bsonType\": \"string\" }\n }\n }\n }\n }\n}\nField Path Error Code Message\nresults.value MissingSchemaType error processing \"type\" property in JSON Schema\n"}, {"role": "assistant", "content": "Text:{ \u201canyOf\u201d: [{ \u201ctype\u201d: \u201cstring\u201d }, { \u201ctype\u201d: \u201cnull\u201d }] }Hi @Sumedha_Mehta1. I tried your recommendation but it doesn\u2019t seems to be working. Below is the schema that I am using:And following is the error I am getting when generating Realm Data ModelsScreenshot 2021-04-13 at 9.25.29 PM1864\u00d7644 65.8 KB\nCode:{\n \"title\": \"BuildingEquipment\",\n \"properties\": {\n \"_id\": { \"bsonType\": \"objectId\"},\n \"configs\": {\n \"bsonType\": \"array\",\n \"items\": {\n \"bsonType\": \"object\",\n \"properties\": {\n \"field\": {\"bsonType\": \"string\"},\n \"value\": { \"anyOf\": [{\"bsonType\": \"string\"}, {\"bsonType\": \"double\"}]}\n }\n }\n }\n }\n}\n"}, {"role": "assistant", "content": "Text:@Dhananjay_PugliaAre you using Sync in this application? That error refers to that service specifically, not GraphQL. GraphQL will just ignore that field in your schema.\nCode:"}, {"role": "assistant", "content": "Text:@Sumedha_Mehta1 Yes I am using Sync in this application. Will this solution not working with Sync? If no then is there any way where I can sync multiple type of data for a single field ?\nCode:"}, {"role": "assistant", "content": "Text:We are working on a way to to introducing this for Sync pretty soon (~1 mo) - you can stay up to date on new data types by subscribing here: Realm Community Projects | Realm.io\nCode:"}, {"role": "assistant", "content": "Text:Great. Thanks a lot @Sumedha_Mehta1 for the update.\nCode:"}, {"role": "assistant", "content": "Text:I see that the \u201cmixed\u201d type has now been added to Realm DB / Sync \u2013 I presume this would now enable you to implement union types in GraphQL? Or has it already been done? @Sumedha_Mehta1\nCode:"}, {"role": "assistant", "content": "Text:Is there any progress on this subject?\nCode:"}, {"role": "assistant", "content": "Text:You can apply multiple types to a field in the schema like this [\u201cstring\u201d, \u201cnull\u201d].\nRefer: https://docs.mongodb.com/realm/schemas/types/\nimg: https://i.imgur.com/vulUoem.pngBut those type will be ignored by the graphql schema generation.\nRefer: https://docs.mongodb.com/realm/graphql/types-and-resolvers/\nimg: https://i.imgur.com/eXxqljz.pngcurrently I cant find a workaround for this.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Restricting user to login from multiple devices and tags: ['app-services-user-auth']"}, {"role": "user", "content": "Text:As per my use case, I need to restrict my end-user to login from single device. I want to implement any one of the following. Assume end-user is already logged in from one device. When user tries to login from second deviceAny of these approach will help me to implement my use case.Thanks\nCode:"}, {"role": "assistant", "content": "Text:Hey Sudarshan -The general approach would be:a) Store the user\u2019s \u201ccurrentDeviceId\u201d every time the user logs in with Custom Function Authentication and Custom User Datab) The next time the user logs in, revoke all sessions from the Admin API in your custom function, before logging them again and setting the user\u2019s new Device ID - this way you get to add your session expiration logic before the user has actually logged in on another device and provided another session token.c) Add client code to handle invalid session requests and take user to logout screenIn practice, this would look like:\ndevice a \u2192 logged in\ndevice b \u2192 calls login function \u2192 -> revokes all sessions and invalidates device a \u2192 logs user in from device b with new session \u2192 user is logged in on device b successfullyany subsequent request will fail, client code handles invalid session and takes user to login screenIf you want to request more session/token configuration options - you can add a request here. We use items here to influence our roadmap on Realm.Sumedha\nCode:"}, {"role": "user", "content": "Text:Thanks for such a detailed approach.Can you please let me know the structure of the parameter, i.e., loginPayload of Custom Function Authentication.\nCode:loginPayload"}, {"role": "assistant", "content": "Text:The function payload will be whatever custom credentials you want to pass in for authentication (e.g. email, password, device Id, etc)There is an example on one of our DevHub posts on how to use Custom Function Auth\nCode:"}, {"role": "assistant", "content": "Text:Hi Sumedha ,\nMentioned DevHub posts \nis not available (404-Not Found). Can please check it once.\nCode:"}, {"role": "assistant", "content": "Text:A quick search on the MongoDB Developer site returns this article has has the same title. I\u2019m pretty sure that MongoDB changed their site around a bit not that long ago so it makes sense that articles were moved to the new location.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Default \"number\" to double \"Double\" type and tags: ['node-js']"}, {"role": "user", "content": "Text:Right now, when I insert a new document from nodejs, number properties are inserted depending on the most fitting type, so 0 are inserted as Int32 but 0.1 as Double.In mongo shell types are defaulted to Double. Is there any way to default all numbers to Double in mongodb nodejs driver? This is giving me some schema validation problems and don\u2019t wall to fill my entire back-end with \"new Double()\"s.\nCode:"}, {"role": "assistant", "content": "Text:Hello @Jorge_Fuentes, welcome to the MongoDB Community forum.What you are saying is correct about the different types for the numbers with NodeJS driver. Can you tell how are you inserting the documents into the collection - I mean the code you are using to insert.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Jorge_Fuentes, welcome onboard!You need to \u201ccast\u201d your value so they are actually Double in JS.Thanks JS for not being a typed language .Cheers,\nMaxime.\nCode:Doublevar Double = require(\"mongodb\").Double;\nvar foo = Double(15) \n"}, {"role": "assistant", "content": "Text:An option is to use a ODM like Mongoose, where you can define a schema with field types. This might work.Here is another possibility - you can define a custom number class which is used throughout the application. This will make sure that the number data is of one specific type (as needed for specific field or fields). This is not an unusual solution. I have studied such solutions for object-oriented applications (e.g., using Java) where a separate class, for example, to represent currency numbers.\nCode:"}, {"role": "user", "content": "Text:Well, I was thinking about a config parameter under the driver options (if it exists), more than using a ODM or redoing part of the backend. As I already said, I don\u2019t want to add Doubles all around the backend when I\u2019m going to work with numbers. Just love to work with plain js.mongo shell has, as per documentation (https://docs.mongodb.com/manual/core/shell-types/), Doubles as default, so I thought that the \u201cconvert to the most-fitting\u201d was a driver thing, not a mongo one. If I have to redo part of the backend I prefer the casting thingy.What I\u2019m using to work with the database are the typical insertOne, updateOne, updateMany, etc\u2026 for example, one item with a property that starts at zero, I now use insertOne({...yadayada, prop: new Double(0)}), which I would like to be insertOne({...yadayada, prop: 0}). I just like to have the less conversion-code or less non-vanilla code as possible. I like to see it as plain as possible.Thank you for your help!\nCode:insertOneupdateOneupdateManyinsertOne({...yadayada, prop: new Double(0)})insertOne({...yadayada, prop: 0})"}, {"role": "assistant", "content": "Text:@Jorge_Fuentes Did you ever find a solution? I\u2019d like to do the same.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: ObjectId in must be a single string of 12 bytes or a string of 24 hex characters on reloading the product page and tags: ['node-js', 'atlas-functions']"}, {"role": "user", "content": "Text:Hey there everyone,\nI was following the jumpstart ecommerce tutorial with mongo db, and I encountered this problem.When I click on the card and go to the product page it works fine, but when i reload the product page it returns an error:`Error: ObjectId in must be a single string of 12 bytes or a string of 24 hex charactersThe realm function for getting the product:Thank you for taking your time out to read this question.Jumpstart https://www.youtube.com/playlist?list=PL4RCxklHWZ9v2lcat4oEVGQhZg6r4IQGV\nScreen Recording of the issue: https://drive.google.com/file/d/12zWMujEl-gb4VyD0zq5uOvMYKeZ_8keu/view?usp=sharingRegards,\nVaarun Sinha\nCode:exports = function(arg){\n\n\n\n let collection = context.services.get(\"mongodb-atlas\").db(\"store\").collection(\"products\");\n \n\n return collection.findOne({_id:BSON.ObjectId(arg)})};\n"}, {"role": "assistant", "content": "Text:Did you find a resolution? Anyone from Mongo can chime in?\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m having the same type of issue. But im trying something like this in an API:\nCode:const value = JSON.stringify(uid)\nconst palette = await db.collection(\"users\").find({ _id: ObjectId(value) }).toArray()\n"}, {"role": "assistant", "content": "Text:When I click on the card and go to the product page it works fine, but when i reload the product page it returns an errorwhen you reload, your page has only what you include in your URL and the things you have saved in the Browser\u2019s cache.In both cases, if you do not properly code what properties will be available to the page and how the page handles them are both left to the developer of the frontend.In your case, it is clear that the page does not do that inside the products page, but relies on the product card to pass the id to it. since the id is not in the form MongoDB expects (most possibly it is just null or undefined) then you get that error.\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m having the same type of issue. But im trying something like this in an API:Your issue has the same error for a different reason. JSON.stringify() will give an error if its arguments is not an object. You don\u2019t seem to get an error in that step so uid is an object, and your value will be something like this:see, the single quotes are surrounding those inner double quotes. you can now see why ObjectId() gave an error. value does not have a proper shape.you have two options now depending on what uid holds.\nCode:JSON.stringify()objectuidvalue='{\"id\":\"someIdValue\"}'\nObjectId()valueuidconst value = uid.id // directly use the id field if it is a proper formatted string\nor\n.....find( { _id : uid.id } ) // directly use the id field if it is a proper object id.\n"}, {"role": "assistant", "content": "Text:I\u2019m still battling this issue. There\u2019s something happening when the document _id is sent from the client to the server. It\u2019s no longer being read as a string even though its typeof value equals string.\nCode:_idtypeofstring"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to install mongodb 6.0 on Ubuntu 22.04 and tags: ['sharding']"}, {"role": "user", "content": "Text:Hello! I try to install mongoDB community server 6.0 on Ubuntu 22.04. Belows are my installation process.But libssl1.1 is not installed and brings the errors when executing the installation.Belows are the error messgaes.So I downloaded the installation deb file from the site and execute it. But the same errors are thrown. Any reply will be thanksful. Best regards\nCode:sudo apt-get update\necho \"deb http://security.ubuntu.com/ubuntu impish-security main\" | sudo tee /etc/apt/sources.list.d/impish-security.list\nsudo apt update\nsudo apt install libssl1.1 --> libssl1.1 is not installed!\n\nwget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list\nsudo apt update\nsudo apt install -y mongodb-org\nmongodb-org-mongos : Depends: libssl1.1 (>= 1.1.1) but it is not installable\n mongodb-org-server : Depends: libssl1.1 (>= 1.1.1) but it is not installable\n mongodb-org-shell : Depends: libssl1.1 (>= 1.1.1) but it is not installable\n"}, {"role": "assistant", "content": "Text:Ubuntu 20.04 is the latest supported Ubuntu.Keep an eye on https://jira.mongodb.org/browse/SERVER-62300Use the supported platform or you can run it in Docker.\nimage826\u00d7209 25.6 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Hi Guys, any update on what 22.04 will be supported?\nCode:"}, {"role": "assistant", "content": "Text:hey guys,the following allowed me to run version 6 on ubuntu-22.10-in-a-docker-image. so in theory it should work on a real installation too.in addition to the steps you followed, do this first:As long as they do not break installed things, \u201carchived\u201d packages should always install and run without a problem. that is what happened in these lines.Yet, keep in mind that, if you break things, the responsibility is yours because MongoDB Community 6 is not yet supported on Ubuntu 22 (is the enterprise version supported? I did not try).PS: I found the package here: Index of /ubuntu/pool/main/o/openssl . there are a few others so check they are applicable instead of the one I use.\nCode:wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1-1ubuntu2.1~18.04.20_amd64.deb\nsudo dpkg -i libssl1.1_1.1.1-1ubuntu2.1~18.04.20_amd64.deb\n"}, {"role": "assistant", "content": "Text:this also works:With this one, it will not even require you to know what to install. it will fetch \u201c1.1.1f-1ubuntu2.16\u201d for amd64. (my other answer used ubuntu2.1~18).\nCode:echo \"deb http://security.ubuntu.com/ubuntu focal-security main\" | sudo tee /etc/apt/sources.list.d/focal-security.list\n"}, {"role": "assistant", "content": "Text:Please check this video\u2026I installed Mongodb on Ubuntu 22.04 by following the step by step instructions from this video: install mongodb in ubuntu 22.04 - YouTube\nCode:"}, {"role": "assistant", "content": "Text:Hi @Silpa_Baburajan , that video installs version 5, so I suggest you check your installation.the OPs first post above has the commands for version 6. It seems adding focal-security to sources.list allows the installation smoothly.\nCode:focal-securitysources.list"}, {"role": "assistant", "content": "Text:As of 6.0.3 mongodb server is built for Ubuntu 22.04.The manual is yet to be updated but very similar to the 20.04 instructions but using jammy in the repo string instead of focal.\nCode:jammyfocalecho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list\n"}, {"role": "assistant", "content": "Text:md64,arm64 ] httpto avoid the apt-key message:\ncurl -sS https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.0.gpg\nCode:md64,arm64 ] httpcurl -sS https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.0.gpg"}, {"role": "assistant", "content": "Text:That is part of the regular install steps in the manual for installing version 6 on ubuntu. No point in recreating the manual in the forum.\nCode:"}, {"role": "assistant", "content": "Text:this man page: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/#platform-support uses apt-key which gave me a warning that apt-key is depreciated. I found this thread because all the other docs/attempts to install mongo on 22.04 failed. Is there a more current install guide to help the next guy?\nCode:"}, {"role": "assistant", "content": "Text:I agree with @Ken_Town ,Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8))apt-key stores all keys in a single /etc/apt/trusted.gpg which seems to have its own issues (thus deprecated). It embeds to this file the .asc key files created with gpg --armorthe suggested way to store key files is to store .gpg files under /etc/apt/trusted.gpg.d/. if we have .asc file then gpg --dearmor takes its content and gives back .gpg content.unless we are supplied directly with .gpg file by MongoDB (so be careful in the future), it is better to usePS: use apt-key list and see any key under /etc/apt/trusted.gpg. use apt-key remove to remove those if you want, and add again with the above method.\nCode:apt-key/etc/apt/trusted.gpg.ascgpg --armor.gpg/etc/apt/trusted.gpg.d/.ascgpg --dearmor.gpg.gpgcurl -sS https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.0.gpg\nor\nwget -qO - https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.0.gpg\napt-key list/etc/apt/trusted.gpgapt-key remove"}, {"role": "assistant", "content": "Text:That is a good point, apt-key is deprecated.However it is only a warning. i.e. Don\u2019t continue to use this its going away, there is a newer way of doing it now. I\u2019m sure it will be addressed when the docs are updated.The point I am making is that until the documentation/manual is updated the only change required to install on Ubuntu 22.04 is changing focal to jammy. There is no additional steps, a very small deviation from what is already documented.If you trace back the release notes and related jiras there is outstanding items relating to updating the documentation.\nCode:focaljammy"}, {"role": "assistant", "content": "Text:I followed the instructions on the video to install MongoDB 6 on Ubuntu 22.04 (replaced focal with jammy and 5.0 and 6.0) but once I started, enabled and checked the status of mongod it gave me \"failed (Result: core-dump). I\u2019m running Ubuntu 22.04 in VirtualBox. I removed the installation thinking I may have done something wrong but got the same result. I don\u2019t know what else to do.\nCode:"}, {"role": "assistant", "content": "Text:step by step for Ubuntu 22.04. full docs here\nCode:sudo apt dist-upgrade\nsudo apt-get install gnupg\nwget -qO - https://pgp.mongodb.com/server-6.0.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.0.gpg\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list\nsudo apt-get update\nsudo apt-get install -y mongodb-org\nsudo systemctl enable mongod\nsudo systemctl start mongod\n\n$ mongosh\nCurrent Mongosh Log ID: 63b77379982aa0dc5c083475\nConnecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1\nUsing MongoDB: 6.0.3\nUsing Mongosh: 1.6.1\n"}, {"role": "assistant", "content": "Text:If you have an old cpu you will need to install version 4. Version 5 and 6 require avx\ngrep flags -m1 /proc/cpuinfo | grep avxI was just testing our MongoDB v17.0 release and Mongo wouldn't start. In fact i\u2026 can't even read it's help or check it's version...:\n\n```\nroot@mongodb ~# mongod --help\nIllegal instruction\nroot@mongodb ~# mongod --version\nIllegal instruction\n```\n\nAfter a bit of searching, I discovered a [bug that sums up the situation](https://jira.mongodb.org/browse/SERVER-59482). A comment from one of the devs notes that v5.0+ has [specific CPU requirements](https://www.mongodb.com/docs/manual/administration/production-notes/#x86_64).\n\nApparently, it could be recompiled to allow v5.0 to run on older x86_64 CPUs, although I'm not keen on doing that.\n\nAnother option is to stick with v4.4 for now?\n\nI guess another option would be to provide 2 appliances, but 2 things; firstly I don't ahve a compatible CPU and I don't think that mongodb is popular enough for that. My inclination is to stick with v4 for now. We could perhaps have a script to upgrade?\n\nFWIW on Linux to check if your CPU can run v5:\n```\ngrep flags -m1 /proc/cpuinfo | grep avx\n```\n(FWIW, that will only check the first CPU core, but AFAIK, that's enough).\nCode:avxgrep flags -m1 /proc/cpuinfo | grep avx"}, {"role": "assistant", "content": "Text:This is a different problem.You should search the forum first and then open a new topic if you don\u2019t find an answer.Both the core-dump/Illegal Instruction and ECONNREFUSED have had much coverage in the forums.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Brew mongodb-community server error and tags: ['installation']"}, {"role": "user", "content": "Text:I am using macOS Big Sur. I have installed mongodb-community@4.4 server on mac recently with help of MongoDB Homebrew Tap. After successful installation, I run \u201cbrew services start mongodb/brew/mongodb-community\u201d on terminal. I receive below result :Successfully started mongodb-community (label: homebrew.mxcl.mongodb-community)But, when I check for running server with \u201cbrew services list\u201d, I get below status :\nmongodb-community error nileshpanhale /Users/nileshpanhale/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plistAnd if I try to connect server with \u201cmongo\u201d shell the I get below error :Error: couldn\u2019t connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :\nconnect@src/mongo/shell/mongo.js:374:17As I am new to macOS and MongoDB. Request you to please help me on an urgent basis with the stepwise solution. Due to this error, my development is completely stopped.Thanks in advance.\nCode:mongodb-community"}, {"role": "assistant", "content": "Text:brew services start mongodb/brew/mongodb-communityIs the command to start services correct\nIt should be something like\nbrew services start mongodb/brew/mongodb-community@4.4\nPlease check documentationUnless your mongod is up you cannot connect to mongodbCan you check mongod.log.It will give more details on why it failed to start\nCould be permissions issue or misssing dbpath dir etc\nCode:"}, {"role": "user", "content": "Text:if we do not mention the community version then the command will take default stable version of MongoDB, mostly latest one.\nTo check logs, I can not run mongod.log command, as mongod is not working with macOS.\nIf there is permissions issue then how can I know that?\nI tried to set/create dbpath but macOS Big Sur won\u2019t allow to modify root directory.\nCode:"}, {"role": "assistant", "content": "Text:I tried to set/create dbpath but macOS Big Sur won\u2019t allow to modify root directory.Yes this is a known issue.They removed access to root dirFirst identify your mongod.conf.It should be under /usr/local\nIf you see the contents of config file it will show your mongo.log path\nIf it is failing due to dbpath issue simply create a directory under your home directory and update your config file\nRestart the service.It should start mongod on default port 27017You can start your own mongod on another port say 28000 by below command\nmongod --port 28000 --dbpath your_dbpath --logpath your_logpath --fork\nGive valid full path for dbpath and logpath where the owner of mongod can writeCheck mongodb documentation and this linkIn this reading I will be helping you step-by-step on setting up MongoDB and make it running\u2026\nReading time: 4 min read\n\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer and tags: ['node-js', 'crud', 'mongoose-odm']"}, {"role": "user", "content": "Text:Hello i have an issue with my code here. Initially my crud on chrome does every work i want but then my update query releases some errors i know nothing of. I have googled for about 4 hours now but nothing. Please i need some help.This is the error i am gettingWhat am trying to say is this i am able to create a new user, read and also delete but the update button works only on my browser and when i console log i get the data i updated but simply doesnt display on my db.\nCode:router.put(\"/skooliva/student/:id\", async (req, res) => {\n const student = {\n fullname: req.body.fullname,\n email: req.body.email,\n mobile: req.body.mobile,\n Date_of_birth: req.body.Date_of_birth,\n ID_number: req.body.ID_number,\n address: req.body.address,\n place_of_birth: req.body.place_of_birth\n }\n \n \n studentPre.findByIdAndUpdate((req.params.id).trim(), { $set: student }, { new: false }, (err,data) => {\n if(!err){\n res.status(200).json({code: 200, message: 'Updated successfully', updateStudent: data})\n // res.send(data);\n }else{\n console.log(err);\n }\n })\n})\n messageFormat: undefined,\n stringValue: '\"[object Object]\"',\n kind: 'ObjectId',\n value: '[object Object]',\n path: '_id',\n reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer\n at new BSONTypeError (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\bson\\lib\\error.js:41:28)\n at new ObjectId (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\bson\\lib\\objectid.js:67:23)\n at castObjectId (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\cast\\objectid.js:25:12)\n at ObjectId.cast (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schema\\objectid.js:246:12)\n at ObjectId.SchemaType.applySetters (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1201:12)\n at ObjectId.SchemaType._castForQuery (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1648:15)\n at ObjectId.SchemaType.castForQuery (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1636:15)\n at ObjectId.SchemaType.castForQueryWrapper (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1612:20)\n at cast (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\cast.js:347:32)\n at model.Query.Query.cast (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\query.js:5312:12),\n valueType: 'string'\n}\n[nodemon] restarting due to changes...\n[nodemon] starting `node index.js`\nserver running\nCastError: Cast to ObjectId failed for value \"[object Object]\" (type string) at path \"_id\" for model \"studentPre\"\n at model.Query.exec (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\query.js:4884:21)\n at model.Query.Query.findOneAndUpdate (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\query.js:3444:8)\n at Function.Model.findOneAndUpdate (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\model.js:2635:13)\n at Function.Model.findByIdAndUpdate (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\model.js:2749:32)\n at C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\routes\\index2.js:73:16\n at Layer.handle [as handle_request] (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at next (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\express\\lib\\router\\route.js:144:13)\n at Route.dispatch (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\express\\lib\\router\\route.js:114:3)\n at Layer.handle [as handle_request] (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\express\\lib\\router\\layer.js:95:5)\n at C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\express\\lib\\router\\index.js:284:15 {\n messageFormat: undefined,\n stringValue: '\"[object Object]\"',\n kind: 'ObjectId',\n value: '[object Object]',\n path: '_id',\n reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer\n at new BSONTypeError (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\bson\\lib\\error.js:41:28)\n at new ObjectId (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\bson\\lib\\objectid.js:67:23)\n at castObjectId (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\cast\\objectid.js:25:12)\n at ObjectId.cast (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schema\\objectid.js:246:12)\n at ObjectId.SchemaType.applySetters (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1201:12)\n at ObjectId.SchemaType._castForQuery (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1648:15)\n at ObjectId.SchemaType.castForQuery (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1636:15)\n at ObjectId.SchemaType.castForQueryWrapper (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\schematype.js:1612:20)\n at cast (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\cast.js:347:32)\n at model.Query.Query.cast (C:\\Users\\user\\OneDrive\\Bureau\\SKOOLIVA_u\\backend\\node_modules\\mongoose\\lib\\query.js:5312:12),\n valueType: 'string'\n}\nconnected successfully\n"}, {"role": "assistant", "content": "Text:Hi @Chi_Samuel,BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integerHopefully you\u2019re not experiencing this error still but based off the error, are any of the ObjectId\u2019s invalid in your code? When an invalid ObjectId() is used, this error generally occurs. E.g.:From a quick initial glance, I can see you trim() the req.params.id value, is this to form it into an ObjectId()? I\u2019m not sure where else the issue could occur as they are from the request itself. Perhaps you could print the values (specifically for ObjectId() fields) that are used when you receive this error and verify they are valid ObjectId()'sRegards,\nJason\nCode:ObjectIdObjectId()DB> ObjectId(\"6348acd2e1a47ca32e79f46f\") /// <--- Valid ObjectId\nObjectId(\"6348acd2e1a47ca32e79f46f\") /// <--- No error\n\nDB> ObjectId(\"6348acd2e1a47ca32e79f46fX\") /// <--- Invalid ObjectId\nBSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer\nreq.params.idObjectId()"}, {"role": "assistant", "content": "Text:thanks for your answer @Jason_Tran! Can you give some examples on how to conveniently check if this ObjectID is valid?\nI\u2019m currently checking it like that, but I don\u2019t really like this answer\nCode:const getUser = (req, res, id) => {\n try {\n ObjectID(id)\n User\n .findById(id)\n .exec((error, user) => {\n if (error) {\n return res.send(error)\n }\n if (user) {\n return res.json(user)\n } else {\n return res.send(`couldnt find user with id ${id}`)\n }\n }) \n } catch(err) {\n return res.send(`couldnt find user with id ${id}`)\n }\n}\n"}, {"role": "assistant", "content": "Text:Can you give some examples on how to conveniently check if this ObjectID is valid?Just to clarify, when you state \u201ccheck if the ObjectID is valid?\u201c, do you mean that the document with a specific ObjectId value exists? Based off your code snippet, I cannot see where an ObjectId validity check is being done. I.e., by \u201cvalid\u201d do you mean:Additionally, could you advise if you\u2019re getting the same error message as the OP?I don\u2019t have any specific examples handy but depending on your driver and driver version (I am assuming node in this case but please correct me if I am wrong here), you may wish to use the isValid() method for ObjectId.Note: docs linked above is for version 4.13 of the Node.JS Driver for MongoDBRegards,\nJason\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB PHP GUI \u2013 A Web interface for MongoDB and tags: ['php']"}, {"role": "user", "content": "Text:I wrote an application (in PHP, JS, HTML and CSS) that allows you to administrate a MongoDB database via a Web browser. Project name is: MongoDB PHP GUI. It is open-source and free. Its features are:\nmpg-database-query1920\u00d71080 98.7 KB\n\nCode:"}, {"role": "user", "content": "Text:v1.0.5 introduces a new feature: You can import documents from a JSON file.new-mpg-collection-import1920\u00d71080 64.1 KB\nCode:"}, {"role": "user", "content": "Text:Since 1.0.6 version you can:newest-mpg-database-visualize1920\u00d71080 90.7 KB\nCode:"}, {"role": "user", "content": "Text:Since 1.0.7 version, you can create and drop users.mpg-manage-users1920\u00d71080 51.9 KB\nCode:"}, {"role": "user", "content": "Text:MongoDB PHP GUI is available at Docker Hub \nCode:"}, {"role": "user", "content": "Text:Before 1.1.6 version, you had to query database with a strict JSON syntax. Example:Since 1.1.6 version, you can query database with a relaxed JSON syntax. Example:\nCode:{ \"firstname\": \"Samuel\" }\nfirstname: Samuel\n"}, {"role": "user", "content": "Text:MongoDB PHP GUI supports now advanced options such as Replica Set in \u201cURI\u201d connection mode. You can switch connection mode on login page:\nCode:"}, {"role": "user", "content": "Text:MongoDB PHP GUI switched to dark theme. I hope you will like it! \nMongoDB PHP GUI - Introducing Dark Theme1920\u00d71080 93 KB\n\nCode:"}, {"role": "assistant", "content": "Text:@Samuel_Tallet, while creating an index through the MongoDB PHP UI does it, will create in background or in the foreground?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoServerError: WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction and tags: ['queries', 'node-js', 'transactions']"}, {"role": "user", "content": "Text:I am getting the the following error when I try to update only 2 documents with the transaction:From all the docs I read, this can be an issue when modifying more than 1000 documents, but since I am updating only 2, it should not throw any error.That being said, this error only happens sometimes, not always. Usually, the logic will pass without the error, but sometimes it is thrown randomly.MongoDB version: 5.0.14Here is the code:I think it\u2019s the following scenario when the error happens:I assume this based on the following paragraph from the docs:If a multi-document transaction is in progress, new DDL operations that affect the same database(s) or collection(s) wait behind the transaction. While these pending DDL operations exist, new transactions that access the same database(s) or collection(s) as the pending DDL operations cannot obtain the required locks and and will abort after waiting maxTransactionLockRequestTimeoutMillis (which defaults to 5ms).I think it can probably be solved by increasing the maxTransactionLockRequestTimeoutMillis , but I wanted to check with the community. If I would increase maxTransactionLockRequestTimeoutMillis config, would that have some further implications?\nCode:MongoServerError: WriteConflict error: this operation conflicted with another operation. Please retry your operation or multi-document transaction.\nexports.setArticleView = async (req, res) => {\n const userId = req.user._id;\n const { article_id } = req.body;\n\n // Start a session\n const session = await mongoose.startSession();\n\n try {\n // Start a transaction\n session.startTransaction();\n\n await ArticleView.create([{ articleId: article_id, user: userId }], { session });\n\n await Article.updateOne({ _id: article_id }, { $inc: { views: 1 } }, { session });\n\n // Commit the transaction\n await session.commitTransaction();\n\n return res.status(200).json({ success: true });\n } catch (error) {\n return res.status(500).json({ success: false });\n } finally {\n // End session\n session.endSession();\n }\n};\nmaxTransactionLockRequestTimeoutMillismaxTransactionLockRequestTimeoutMillismaxTransactionLockRequestTimeoutMillis"}, {"role": "assistant", "content": "Text:Just a guess, but I\u2019d think you\u2019d have to commit the created document before you try to update it.\nCode:"}, {"role": "user", "content": "Text:Hi @Jack_Woehr, thanks for the answer!I am not sure what do you mean? I am creating document in one collection, and then updating document from other collection. It\u2019s not like I am updating the same document that I created (even though I think that should work too).That being said, this error only happens sometimes, not always. Usually, the logic will pass without the error, but sometimes it is thrown randomly. (I just figured I didn\u2019t mention this in the question itself and I think it\u2019s important. Will updated the question).\nCode:"}, {"role": "assistant", "content": "Text:is the system actually in production? Is other activity taking place?\nCode:"}, {"role": "user", "content": "Text:@Jack_Woehr Yup, it\u2019s in production. No, this is the whole business logic in that endpoint.\nCode:"}, {"role": "assistant", "content": "Text:Well, there certainly are a lot of caveats about transactions!\nUnless someone posts with an answer, I suggest you read carefully both of the following:If you don\u2019t find anything there, you may need to file an issue.\nCode:"}, {"role": "user", "content": "Text:Thanks for the references! I already read them, but I couldn\u2019t figure out what could be the exact issue.I assume it\u2019s maybe the following scenario:I assume this based on the following paragraph from the docs:If a multi-document transaction is in progress, new DDL operations that affect the same database(s) or collection(s) wait behind the transaction. While these pending DDL operations exist, new transactions that access the same database(s) or collection(s) as the pending DDL operations cannot obtain the required locks and and will abort after waiting maxTransactionLockRequestTimeoutMillis (which defaults to 5ms).I think it can probably be solved by increasing the maxTransactionLockRequestTimeoutMillis, but I wanted to check with the community too.\nCode:maxTransactionLockRequestTimeoutMillismaxTransactionLockRequestTimeoutMillis"}, {"role": "assistant", "content": "Text:@steevej do you know the answer to @NeNaD 's question?\nCode:"}, {"role": "assistant", "content": "Text:Thanks for tagging me. I have seen the post but have nothing to add at this moment. I still have not enough experience with transactions to have experimented this issue. In addition, it is with mongoose which I avoid.The only thing I would do it to try without mongoose. The issue might be mongoose.And as I write, I think that this code can should be done outside a transaction. You just create the ArticleView and if successful you $inc the Article/views. $inc is already atomic so if 2 ArticleView are created at the same time, which is also atomic, the count in $inc twice. The issue with transaction in this case, I think, is that you have 2 transactions starting at the more or less the same time. Both transaction take a snapshot of Article. One of the transaction terminate correctly. But now the snapshot of Article of the 2nd transaction is stale as it has been updated by the first transaction.I thought I had nothing to write. Thanks for letting me know I had.\nCode:"}, {"role": "user", "content": "Text:Hi @steevej,Thanks for the response, and @Jack_Woehr thanks for tagging him.I don\u2019t think the issue is related to Mongoose at all, since Error clearly say it\u2019s MongoServerError. Also, I don\u2019t want do it without a transaction because I am tracking unique user views, so it could happen that ArticleView will be created and later it would fail to increase the article\u2019s view count, which would lead to data inconsistency. Thank you for the answer though. \nCode:MongoServerErroruniqueArticleView"}, {"role": "user", "content": "Text:@Stennie_X, @MaBeuLux88, @Pavel_Duchovny, @Jason_TranCan you please let me know your opinions on this if you don\u2019t mind.Thank you in advance! \nCode:"}, {"role": "assistant", "content": "Text:The only wayit would fail to increase the article\u2019s view countis that if the code crashes between the ArticleView creation and the Article.views increment.But if you want to stick with transaction you have to do what the error message tells you to doPlease retry your operation or multi-document transaction.\nCode:Please retry your operation or multi-document transaction."}, {"role": "user", "content": "Text:Yup, I will implement retry logic, it\u2019s just this error should not be thrown in the first place in my opinion, and that is why I raised the question.I am trying to figure out if the maxTransactionLockRequestTimeoutMillis config is the reason for the error, and if the error can be prevented by increase it (if yes, would that have some further implications\u2026). \nCode:retrymaxTransactionLockRequestTimeoutMillis"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Guid in _id in collection and tags: ['dot-net', 'crud']"}, {"role": "user", "content": "Text:Hi Team, Please find below error for inserting document from .Net to MongoDb Collection.\u201869f2cd42-b6a4-418f-a4c2-ece3d719ed6f\u2019 is not a valid 24 digit hex string.Id Property is string GUID which is accepting when I am inserting document from MongoDbCompass or web Collection Explorer but whenever we insert the same from .net code, it generating exception.Details Exception:\nCode: at MongoDB.Bson.ObjectId.Parse(String s)\n at MongoDB.Bson.Serialization.Serializers.StringSerializer.SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, String value)\n at MongoDB.Bson.Serialization.Serializers.SealedClassSerializerBase`1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value)\n at MongoDB.Bson.Serialization.Serializers.SerializerBase`1.MongoDB.Bson.Serialization.IBsonSerializer.Serialize(BsonSerializationContext context, BsonSerializationArgs args, Object value)\n at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize(IBsonSerializer serializer, BsonSerializationContext context, Object value)\n at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.SerializeNormalMember(BsonSerializationContext context, Object obj, BsonMemberMap memberMap)\n at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.SerializeClass(BsonSerializationContext context, BsonSerializationArgs args, TClass document)\n at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TClass value)\n at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Serialize[TValue](IBsonSerializer`1 serializer, BsonSerializationContext context, TValue value)\n at MongoDB.Driver.OperatorUpdateDefinition`2.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)\n at MongoDB.Driver.CombinedUpdateDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)\n at MongoDB.Driver.CombinedUpdateDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)\n at MongoDB.Driver.CombinedUpdateDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)\n at MongoDB.Driver.CombinedUpdateDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)\n at MongoDB.Driver.CombinedUpdateDefinition`1.Render(IBsonSerializer`1 documentSerializer, IBsonSerializerRegistry serializerRegistry)\n at MongoDB.Driver.MongoCollectionImpl`1.ConvertWriteModelToWriteRequest(WriteModel`1 model, Int32 index)\n at System.Linq.Enumerable.d__174`2.MoveNext()\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\n at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation..ctor(CollectionNamespace collectionNamespace, IEnumerable`1 requests, MessageEncoderSettings messageEncoderSettings)\n at MongoDB.Driver.MongoCollectionImpl`1.CreateBulkWriteOperation(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options)\n at MongoDB.Driver.MongoCollectionImpl`1.d__30.MoveNext()\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\n at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()\n at MongoDB.Driver.MongoCollectionImpl`1.d__106`1.MoveNext()\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\n at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()\n at MongoDB.Driver.MongoCollectionBase`1.d__107.MoveNext()\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\n at Core.User.Infrastructure.NoSql.MongoDb.User.Repositories.UserRepository.d__4.MoveNext() in\n"}, {"role": "assistant", "content": "Text:is not a valid 24 digit hex string.Decorate your id property field with the following annotation.\nCode:[BsonRepresentation(BsonType.ObjectId)]"}, {"role": "user", "content": "Text:Still not worked:Property:JSON working when inserting from MongoDbCompass:\nCode: [BsonId]\n [BsonRepresentation(BsonType.ObjectId)]\n [JsonProperty(\"id\")]\n public string Id { get; set; }\n {\n \"_id\": \"69f2cd42-b6a4-418f-a4c2-ece3d719ed6f\",\n \"UserName\": \"SC1005\",\n \"EmailID\": \"abc@test.com\",\n \"Password\": \"APt/zqxocK9haWvu5Iv8+NgWSUuWzep8HrFFRcSkrOveYsBVQDYn7YfxFRVE99R8Mw==\",\n \"FullName\": \"Pravin Yadav\",\n \"LastPwdChangedDateTime\": \"2021-08-09T12:54:05.62+05:30\",\n \"UserGroup\": {\n \"_id\": \"69f2cd42-b6a4-418f-a4c2-ece3d719ed6f\",\n \"GroupName\": \"Administrator\"\n },\n \"UserVisibility\": {\n \"_id\": \"69f2cd42-b6a4-418f-a4c2-ece3d719ed6f\",\n \"GroupName\": \"Administrator\"\n },\n \"ShowLocalLanguage\": false,\n \"CreatedDetails\": {\n \"UserId\": \"69f2cd42-b6a4-418f-a4c2-ece3d719ed6f\",\n \"SessionId\": \"69f2cd42-b6a4-418f-a4c2-ece3d719ed6f\",\n \"UserName\": \"SC1005\",\n \"Timestamp\": \"2021-08-09T12:54:05.62+05:30\"\n }\n }\n"}, {"role": "assistant", "content": "Text:Could you please share the data model?\nCode:"}, {"role": "user", "content": "Text:This is DataModel:\nCode:public class UserResponse\n {\n private UserResponse()\n {\n }\n\n public UserResponse(string id, string userName, string emailID, string password, string fullName, UserGroupResponse userGroup, UserVisibilityResponse userVisibility, bool showLocalLanguage, DateTimeOffset? lastPwdChangedDateTime, bool active, bool isDeleted, ActivityDetails createdDetails, ActivityDetails lastUpdatedDetails)\n {\n Id = id;\n UserName = userName;\n EmailID = emailID;\n Password = password;\n FullName = fullName;\n UserGroup = userGroup;\n UserVisibility = userVisibility;\n ShowLocalLanguage = showLocalLanguage;\n LastPwdChangedDateTime = lastPwdChangedDateTime;\n Active = active;\n IsDeleted = isDeleted;\n CreatedDetails = createdDetails;\n LastUpdatedDetails = lastUpdatedDetails;\n }\n\n [BsonId]\n [BsonRepresentation(BsonType.ObjectId)]\n [JsonProperty(\"id\")]\n public string Id { get; set; }\n public string UserName { get; set; }\n public string EmailID { get; set; }\n public string Password { get; set; }\n public string FullName { get; set; }\n public UserGroupResponse UserGroup { get; set; }\n public UserVisibilityResponse UserVisibility { get; set; }\n public bool ShowLocalLanguage { get; set; }\n public DateTimeOffset? LastPwdChangedDateTime { get; set; }\n public bool Active { get; set; }\n public bool IsDeleted { get; set; }\n public ActivityDetails CreatedDetails { get; set; }\n public ActivityDetails LastUpdatedDetails { get; set; }\n }"}, {"role": "user", "content": "Text:@Sudhesh_Gnanasekaran any luck on this or workaround. Please suggest !!\nCode:"}, {"role": "assistant", "content": "Text:[BsonRepresentation(BsonType.ObjectId)]@Pravin_Yadav you need to decorate the model with this attribute [BsonId].\nCode:[BsonRepresentation(BsonType.ObjectId)] public class UserResponse\n {\n [BsonId]\n public string Id { get; set; }\n\n public string UserName { get; set; }\n }\n\n static void Main(string[] args)\n {\n MongoClient dbClient = new MongoClient(\"mongodb://localhost:27017\");\n var database = dbClient.GetDatabase(\"test\");\n database.GetCollection(nameof(UserResponse)).InsertOne(new UserResponse { Id = Guid.NewGuid().ToString(), UserName = \"Test User\" }); \n }"}, {"role": "user", "content": "Text:Hi Sir,I have tried the same but still getting same error i.e. \u201869f2cd42-b6a4-418f-a4c2-ece3d719ed6f\u2019 is not a valid 24 digit hex string.\nCode:"}, {"role": "assistant", "content": "Text:@Pravin_Yadav did you try to the run the code that I replied? By the way what is your c# driver and mongodb version.?\nCode:"}, {"role": "user", "content": "Text:Yes, tried the same. Below is MongoDb Driver:\n\nand DotNet 5\nCode: private readonly IMongoDatabase _db;\n private readonly IMongoCollection _collection;\n private readonly MongoClient _client;\n public UserRepository(MongoClient client)\n {\n _client = client;\n _db = _client.GetDatabase(\"UserDatabase\");\n _collection = _db.GetCollection(\"Users\");\n }\n\n public void Add(UserResponse item, CancellationToken cancellationToken)\n {\n _collection.InsertOne(item);\n }\n"}, {"role": "user", "content": "Text:@Sudhesh_Gnanasekaran sir, any update or work arround !!\nCode:"}, {"role": "assistant", "content": "Text:Were we able to solve this issue? I am getting the same error message.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB Upgrade from 4.2 and 4.4 to 6.0 and tags: ['upgrading']"}, {"role": "user", "content": "Text:Hello, We are planning to upgrade mongdb on various servers. Few questions.\nCode:"}, {"role": "assistant", "content": "Text:When upgrading you can\u2019t skip major versions you have to go from 4.2 \u2192 4.4 \u2192 5.0 \u2192 etc.\nhttps://www.mongodb.com/docs/manual/release-notes/6.0-upgrade-replica-set/\n\nimage826\u00d7191 8.64 KB\nHere are the release notes for 6.0 and it will mention in a version if there are any issues that would make it not recommended for prod. https://www.mongodb.com/docs/manual/release-notes/6.0/#std-label-release-notes-6.0Make sure to validate your application driver is compatible with the version of MongoDB you are using\nhttps://www.mongodb.com/docs/drivers/driver-compatibility-reference/When you say backup and restores which technology are you referencing?Here is the page that each version of MongoDB and the OS version that is supported\nhttps://www.mongodb.com/docs/manual/administration/production-notes/#platform-support-matrix\nCode:"}, {"role": "user", "content": "Text:I use mongodump in batch files for daily backps.\nCode:"}, {"role": "user", "content": "Text:Thanks alot for your detailed reply\nCode:"}, {"role": "assistant", "content": "Text:It that case I would look into the mongodump/restore docs as it says to restore/dump to the same major version of MongoDB.\nimage815\u00d7274 21.5 KB\n\nCode:"}, {"role": "user", "content": "Text:Thank you. I was able to upgrade successfully until 5. Looka like mongo.exe is not available at 6. How do I start mongoshell with 6?\nCode:"}, {"role": "assistant", "content": "Text:Hi @AnaMongosh is available from the download center, link is in the instructions below.\nCode:"}, {"role": "user", "content": "Text:Thanks, appreciate it. I am able to u[grade to 6 but it is asking for driver update when I was testing application. Any help on this?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Org.mongodb.driver.cluster: Exception in monitor thread while connecting to server 1 and tags: ['java', 'connecting']"}, {"role": "user", "content": "Text:\u52a0\u8f7d\u66f4\u591a\nCode:021-02-20 16:37:56.238 INFO 19488 --- [169.4.200:30510] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server 192.169.4.200:30510\n\ncom.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message\nat com.mongodb.internal.connection.InternalStreamConnection.translateReadException(InternalStreamConnection.java:562) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:447) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:298) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:258) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:103) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:60) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:131) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat java.lang.Thread.run(Thread.java:748) [na:1.8.0_282]\nCaused by: java.net.SocketTimeoutException: Read timed out\nat java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_282]\nat java.net.SocketInputStream.socketRead(SocketInputStream.java:116) ~[na:1.8.0_282]\nat java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_282]\nat java.net.SocketInputStream.read(SocketInputStream.java:141) ~[na:1.8.0_282]\nat com.mongodb.internal.connection.SocketStream.read(SocketStream.java:109) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:579) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:444) ~[mongodb-driver-core-4.0.5.jar!/:na]\n... 9 common frames omitted\n\n2021-02-20 16:37:58.970 WARN 19488 --- [onPool-worker-4] org.mongodb.driver.connection : Got socket exception on connection [connectionId{localValue:5, serverValue:104}] to 192.169.4.200:30510. All connections to 192.169.4.200:30510 will be closed.\n2021-02-20 16:37:58.993 INFO 19488 --- [onPool-worker-4] org.mongodb.driver.connection : Closed connection [connectionId{localValue:5, serverValue:104}] to 192.169.4.200:30510 because there was a socket exception raised by this connection.\n2021-02-20 16:37:58.996 INFO 19488 --- [169.4.200:30510] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server 192.169.4.200:30510\n\ncom.mongodb.MongoSocketOpenException: Exception opening socket\nat com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:127) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat java.lang.Thread.run(Thread.java:748) [na:1.8.0_282]\nCaused by: java.net.ConnectException: \u62d2\u7edd\u8fde\u63a5 (Connection refused)\nat java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_282]\nat java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_282]\nat java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_282]\nat java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_282]\nat java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_282]\nat java.net.Socket.connect(Socket.java:607) ~[na:1.8.0_282]\nat com.mongodb.internal.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:63) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.SocketStream.initializeSocket(SocketStream.java:79) ~[mongodb-driver-core-4.0.5.jar!/:na]\nat com.mongodb.internal.connection.SocketStream.open(SocketStream.java:65) ~[mongodb-driver-core-4.0.5.jar!/:na]\n... 3 common frames omitted\n\n2021-02-20 16:37:59.036 INFO 19488 --- [ main] ConditionEvaluationReportLoggingListener : \n\nError starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.\n2021-02-20 16:37:59.115 ERROR 19488 --- [ main] o.s.boot.SpringApplication : Application run failed\n\njava.lang.IllegalStateException: Failed to execute ApplicationRunner\nat org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:789) ~[spring-boot-2.3.3.RELEASE.jar!/:2.3.3.RELEASE]\nat org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:776) ~[spring-boot-2.3.3.RELEASE.jar!/:2.3.3.RELEASE]\nat org.springframework.boot.SpringApplication.run(SpringApplication.java:322) ~[spring-boot-2.3.3.RELEASE.jar!/:2.3.3.RELEASE]\nat ai.plantdata.graph.excel.ExcelApplication.main(ExcelApplication.java:59) [classes!/:1.4.2]\nat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_282]\nat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_282]\nat sun.refle\n"}, {"role": "assistant", "content": "Text:any solution for this ?\nCode:"}, {"role": "assistant", "content": "Text:Hi! Welcome to the forums! So, we would need more clarifying information to help with this. What versions are you using of the Java driver, MongoDB, and Java? What is causing the timeout? Do you have any code to repro steps? And can you be more specific with the question? Thank you.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: High number of connections and opcounters without anyone using the cluster and tags: ['atlas-device-sync', 'monitoring']"}, {"role": "user", "content": "Text:\nCaptura de Tela 2020-12-17 a\u0300s 16.50.371595\u00d7565 49.7 KB\nThe screenshot shows a period of 0 users on an Atlas Cluster linked with a MongoDB Realm app. As you can see, the second shard shows ~3 commands and ~2 getmores per second with ~60 active connections, and the other two shards maintain the same amount of commands and active connections as the second one, even though they have 0 of any other type of operation. This behavior is constant, the command operation never gets to 0.Is this considered normal behavior for a cluster linked with Realm?\nCaptura de Tela 2020-12-17 a\u0300s 17.28.501595\u00d7565 62.4 KB\nNow, this second image shows a period when some users (less than 3) start using the cluster by a MongoDB Realm Sync .NET client. Should the getmore operation go to ~5.5 per second and stay there constantly? And should the active connections go from 47 to 70 with 3 users connecting?\nCode:"}, {"role": "assistant", "content": "Text:Did you ever gain any insight to this? I\u2019m seeing similar things \u2013 a very large number of connections with minimal to no known active use.\nCode:"}, {"role": "user", "content": "Text:Hi @Eve_Ragins, after I created this topic I did a lot of testing and got in contact with someone from the support team. The answer is not really straightforward.This is what the support said:Connections from a Realm to the Realm servers from a client, including multiple connections are combined in to a single connection, meaning you could have multiple connections from a device/client and that this would not translate into the same number of connections to Atlas.Further new devices connecting to Realm may not result in a new connection being made to Atlas from Realm Servers, it may re-use a connection.\nThe way to look at it would be.Multiple/Single Realms/Devices make a connection to the Realm Servers, these connections are bundled in to a singular connection from Realm Servers to Atlas to service all requests.To minimize the number of concurrent listening clients and open change streams:So the connections count is not 1:1 based on either the number of clients or the number of open Realms. Unused connections can stay active on Atlas and later be reused by another Realm client.A connection is always active for each Atlas collection too, so if you have an Atlas database with 10 synced Realm collections, there will be at least 10 active connections.\nCode:"}, {"role": "assistant", "content": "Text:Thank you for sharing!Unfortunately, that doesn\u2019t seem to align with what I\u2019m seeing\u2026\nI noticed something earlier today about growing connections which I put into this post: Realm does not seem to close mongodb connections on app redeploymentI\u2019ll probably end up opening a support ticket and will share what I learn.\nCode:"}, {"role": "assistant", "content": "Text:@Eve_RaginsDo you have any updates about the connections? I\u2019m having something very similar on my App. Every time I run some function on the realm app, I\u2019m observing that it increases the number of connections; a single client is consuming 140 connections.If you have some updates on this, please share, thanks =)\nCode:"}, {"role": "assistant", "content": "Text:@Loe_LoboThe response I received on August 9th was:We believe that this issue might be related to changes that were introduced last week in MongoDB Realm. We cache MongoDB client connections in a resource pool on each of our servers (to prevent the creation of new connections for every DB request), we made some internal adjustments to how we cache these connections, like when they are evicted, etc. that resulted in additional connections being created unnecessarily.Later on the 12th I received an update:Thank you for your patience. It seems that the latest MongoDB Realm has incorporated the changes required to close idle connections.My connections have dropped from the peak of 700s down to around 178 now. 178 is still extremely high for the number of clients I have (including triggers); but it seems to be holding steady and isn\u2019t a red alert issue for me anymore.Maybe Realm just likes to keep a connection pool of ~150+? I\u2019m pretty new to mongo so I don\u2019t really know how it works or optimizes that \u2013 I did see one stack overflow post that implied 1 connection really turns into 4 connections on a standard 3-database replica set. \nCode:"}, {"role": "assistant", "content": "Text:It definitely looks like this is still an issue. One of my realm apps is now consuming 400+ connections, and it keeps increasing with every new deployment via github.\nScreen Shot 2021-08-30 at 14.18.383584\u00d7922 242 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Same issues here\u2026\nCode:"}, {"role": "assistant", "content": "Text:Hello everybody! I\u2019m very excited to be of assistance!I\u2019m Brock, I am one of the Technical Service Engineers for MongoDB Realm. Please allow me to explain what in particular you\u2019re seeing if I may.Short summary:\nSo simply put, the connections themselves aren\u2019t client connections that you\u2019re seeing. What you\u2019re seeing is a series of redundant connection pathways that are waiting on more and more clients. As you get more clients the connections will begin to even out and disperse to balance the loads of an ever increasing number of clients. (Clients = Users/Devices/Instances of your app)General points:In long summary:\nIf you are using Realm Triggers/functions/Sync, connection count in Atlas connections will increase but that should stabilise after some time(10-15 minutes) of no activity.If you continue to experience any further issues with the connections not being released by the Realm application please let us know Realm app link and we would be happy to look into this further.Realm internally proxies connection by default and keeps them open across multiple invocations so this will definitely be more efficient with connection utilization and may actually be more performant on average (less of a latency hit for opening new connections). Realm generally opens a single connection pool per Realm host and manages connections at the Realm host-level.Further new devices connecting to Realm may not result in a new connection being made to Atlas from Realm Servers, it may re-use a connection.So in another way to explain in short summary, connections count is not directly proportional on either the number of clients or the number of currently open Realms. Some unused connections can stay active on Atlas and later be reused by another Realm client.To minimize the number of concurrent listening clients and open change streams:\nCode:"}, {"role": "assistant", "content": "Text:Brock,Thank you for the quick detailed response.I completely understand the architect behind how the connections get made and thanks for clearing that side of it up.This is the part I don\u2019t understand.What you\u2019re seeing is a series of redundant connection pathways that are waiting on more and more clients.Example:Hopefully, this cleared up what\u2019s going on. The additional connections made are understood, so for example, I log in to my Realm app as ONE client, but it actually makes 10 connections. Understood.But over a little bit of time, those connections that aren\u2019t being used OR if the exact same client re-connects, connections should NOT just keep piling up. Either the existing connections that have been created should be used OR those connections should be dropped and new ones created for this instance.As for the below, I\u2019m not using Watch or Sync.To minimize the number of concurrent listening clients and open change streams:\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m having what seems to be the same issue. I\u2019m relatively new to Realm and MongoDB and still learning the platform. As such, I only have one or two test clients running at a time and the app has only 3 very small collections to sync with.Today, I received numerous email alerts for getting close to the 500 connection limit when I know there hasn\u2019t been a connected client in over 12 hours. Currently it\u2019s showing 400+ connections and I haven\u2019t connected an app at all day. All of this seems like something new since I\u2019ve been playing with Realm for weeks up until without receiving these alerts. At any rate, the # of connections never seems to really go down.\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m seeing this issue myself, and have two Realm apps eating up about 450/500 of my connections \u2013 at least, that\u2019s what I\u2019m thinking since it seems to hover at that level even with a solid hour of having nothing set in the NACL.@Brock_GL Are there any quick fixes here? Will these connections be released if I delete my Realm applications?\nCode:"}, {"role": "assistant", "content": "Text:Same issue here and I reported it to support who opened an internal ticket. What I did in the meantime was to create a new Cluster and restore the most recent database snapshot back to the new cluster. I then switched my Realm app to the new cluster. I still get a jump of 50+ connections every time I do a deployment but it will keep me going until the problem gets solved properly.That was all fine on my dev environment but I can see the same problem building up on my prod environment where I\u2019ve temporarily stopped doing deployments for fear of pushing the system over the connection limit and bringing the website down.\nCode:"}, {"role": "assistant", "content": "Text:I deleted the application, waited 10 minutes, the connections were still there. The temporary solution was to do as @ConstantSphere said: a new cluster and application with limited operations on it\u2026 I hope it is an issue from server side, because I\u2019m feeling hopeless\u2026\nCode:"}, {"role": "assistant", "content": "Text:Besides, the operation count are also non zero when no users are connected. Somehow, it seems each user opens a number of connections that are kept active and asking for data each second. Maybe that\u2019s why the connections are not being released (just a guess).\nCode:"}, {"role": "assistant", "content": "Text:I see this morning that Enable Automatic Deployments has been disabled on my Realm app both in development and production and I can\u2019t switch it back on. I tried updating a function via the UI and deploying the changes (in dev) and I still got a big jump in connections (despite it not linking back to GitHub).\nCode:"}, {"role": "assistant", "content": "Text:About 15 hours ago the number connections on my dev environment fell significantly. I did a deployment to it earlier and it jumped up again so I\u2019m not sure if the issue is completely fixed but I\u2019ve now got head room on my production system to resume deployments again. \nCode:"}, {"role": "assistant", "content": "Text:I just did another deployment to my dev environment and unfortunately the number of connections went up again so I don\u2019t think the issue is completely resolved. Perhaps they\u2019ll all get closed down again tonight?\nCode:"}, {"role": "assistant", "content": "Text:Hello, I am also experiencing the same issue as everyone else. I have made a realm application before about a year ago and did not encounter anything like this before. The connections graph would drop down once a user had closed the application (once you see the realm disconnected message in the console output).2021-09-19 09:56:16.234516-0400 APP_NAME[10099:675941] Sync: Connection[2]: DisconnectedIn the application I am currently developing I am using more functions and triggers which could be the cause of this problem. Maybe when you open a MongoDB Function/Trigger, the connection from there does not get closed and stays active? The reason I say this is because I was just using the MongoDB Realm Functions page for editing and testing a single function and my connections skyrocketed! Its like the function was creating connections that never get disconnected.\nScreen Shot 2021-09-19 at 11.39.54 AM2452\u00d7988 188 KB\nYou can see the connections at the beginning of the project are super low because I was not using any functions or triggers at the time and the only connection was the realm connection coming from the device (which got disconnected after use). But once I started to implement functions and triggers, the connections went through the roof. Im assuming they go down after a day or two, but a day or two just to disconnect the connection from a function/trigger (I may be completely mistaken on how that works) ???As I am just in development mode, is there a way to disconnect all connections from the database?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Filtering multiple nested ObjectId's and tags: ['aggregation', 'queries', 'node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:Product Model:Variation Model:I tried to find() using mongodb with both of the filters below:{ variations: { '$elemMatch': { color: '639b75a799cf2ed9eb2802ec' } } }\n{ \"variations.color\": \"639b75a799cf2ed9eb2802ec\" }neither worked. any idea?\nCode:{\n ...\n department: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Department\",\n required: true,\n },\n category: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Category\",\n required: true,\n },\n variations: [\n {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Variation\",\n },\n ],\n ...\n}\n{\n color: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Color\",\n required: true,\n },\n size: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Size\",\n required: true,\n },\n ...\n}\nfind(){ variations: { '$elemMatch': { color: '639b75a799cf2ed9eb2802ec' } } }{ \"variations.color\": \"639b75a799cf2ed9eb2802ec\" }"}, {"role": "assistant", "content": "Text:Because your types are ObjectId and\u2018639b75a799cf2ed9eb2802ec\u2019is a string. Types and values must match.\nCode:"}, {"role": "user", "content": "Text:mongoose.Types.ObjectId(\"639b75a799cf2ed9eb2802ec\") didn\u2019t work either\nCode:mongoose.Types.ObjectId(\"639b75a799cf2ed9eb2802ec\")"}, {"role": "assistant", "content": "Text:Please share sample documents from both collection.Share exactly the code that you have tried.\nCode:"}, {"role": "user", "content": "Text:Product Document:Variation with id 63a48b89cd827b16f31ac9b9 document:Color with id 6398fbdb1fc0f2835e898a91 document:My API:\nCode:{\n \"_id\": {\n \"$oid\": \"63a48b89cd827b16f31ac9b2\"\n },\n \"name\": \"Ali's Boxers\",\n \"description\": \"Boxers made specifically for ALi\",\n \"department\": {\n \"$oid\": \"6398fbf11fc0f2835e898aa8\"\n },\n \"category\": {\n \"$oid\": \"6398fbfd1fc0f2835e898aae\"\n },\n \"variations\": [\n {\n \"$oid\": \"63a48b89cd827b16f31ac9b9\"\n },\n {\n \"$oid\": \"63a48b8acd827b16f31ac9c1\"\n }\n ],\n \"price\": 50,\n \"discount\": 0,\n \"identifier\": \"A\",\n \"createdAt\": {\n \"$date\": {\n \"$numberLong\": \"1671728010297\"\n }\n },\n \"updatedAt\": {\n \"$date\": {\n \"$numberLong\": \"1671728010297\"\n }\n },\n \"__v\": 0\n}\n63a48b89cd827b16f31ac9b9{\n \"_id\": {\n \"$oid\": \"63a48b89cd827b16f31ac9b9\"\n },\n \"color\": {\n \"$oid\": \"6398fbdb1fc0f2835e898a91\"\n },\n \"size\": {\n \"$oid\": \"6398fbe61fc0f2835e898aa1\"\n },\n \"stock\": [\n {\n \"$oid\": \"63a48b89cd827b16f31ac9b5\"\n }\n ],\n \"images\": {\n \"$oid\": \"63a48b89cd827b16f31ac9b3\"\n },\n \"createdAt\": {\n \"$date\": {\n \"$numberLong\": \"1671728009397\"\n }\n },\n \"updatedAt\": {\n \"$date\": {\n \"$numberLong\": \"1671728009397\"\n }\n },\n \"__v\": 0\n}\n6398fbdb1fc0f2835e898a91{\n \"_id\": {\n \"$oid\": \"6398fbdb1fc0f2835e898a91\"\n },\n \"name\": \"red\",\n \"code\": \"#d44a4a\",\n \"skuCode\": \"001\",\n \"createdAt\": {\n \"$date\": {\n \"$numberLong\": \"1670970331140\"\n }\n },\n \"updatedAt\": {\n \"$date\": {\n \"$numberLong\": \"1671006396023\"\n }\n },\n \"__v\": 0\n}\nexports.getAll = async (req, res) => {\n try {\n const { offset, limit } = req.query;\n const offsetInt = parseInt(offset) || 0;\n const limitInt = parseInt(limit) || 15;\n\n const queryObj = buildProductQuery(req.query);\n\n const products = await Product.find(queryObj)\n .limit(limitInt)\n .skip(offsetInt)\n .populate(populateQuery);\n\n const totalProductsCount = await Product.countDocuments(queryObj);\n const totalPages = Math.ceil(totalProductsCount / limitInt);\n const currentPage = Math.ceil(offsetInt / limitInt) + 1;\n\n return Response.success(res, {\n products,\n pagination: {\n total: totalProductsCount,\n pages: totalPages,\n current: currentPage,\n },\n });\n } catch (err) {\n return Response.serverError(res, err.message);\n }\n};\n\nconst buildProductQuery = (query) => {\n const { department, category, color, size } = query;\n\n const queryObj = {\n variations: { $ne: [] },\n\n ...(department && { department }),\n ...(category && { category }),\n\n // I tried 2 ways of filtering, you can uncomment the below 2 lines and comment the next block to switch between the 2 (neither worked)\n // I have also tried casting to `mongoose.Types.ObjectId` on both options.\n\n // ...(color && { \"variations.color\": color }),\n // ...(size && { \"variations.size\": size }),\n\n ...((color || size) && {\n variations: {\n $elemMatch: {\n ...(color && { color: mongoose.Types.ObjectId(color) }),\n ...(size && { size: mongoose.Types.ObjectId(size) }),\n },\n },\n }),\n };\n\n console.log(queryObj);\n return queryObj;\n};\n"}, {"role": "assistant", "content": "Text:I have just realized that you are using mongoose. I guess I do not really look at the post tags.Sorry, but I do not know how mongoose work. Hopefully someone with knowledge in this area will pick up.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Emile_Ibrahim , There is no problem with how you convert ObjectId. The problem is probably about how you use them throughout your document.It is possible documents are not populated. can you give output for Product.findOne({})?also, what is populateQuery and the result for Product.findOne({}).populate(populateQuery)?\nCode:Product.findOne({})populateQueryProduct.findOne({}).populate(populateQuery)"}, {"role": "user", "content": "Text:Hello sorry for the late response. Happy Holidays!My populate query is:Product.findOne({}) is:Product.findOne({}).populate(populateQuery) is:\nCode:const populateQuery = [\n {\n path: \"department\",\n model: Department,\n },\n {\n path: \"category\",\n model: Category,\n },\n {\n path: \"variations\",\n model: Variation,\n populate: [\n {\n path: \"color\",\n model: Color,\n },\n {\n path: \"size\",\n model: Size,\n },\n {\n path: \"stock\",\n model: Stock,\n populate: [\n {\n path: \"materials.material\",\n model: Material,\n },\n {\n path: \"labourCost\",\n model: LabourCost,\n },\n ],\n },\n {\n path: \"images\",\n model: ProductImages,\n populate: [\n {\n path: \"images\",\n model: \"Image\",\n },\n ],\n },\n ],\n },\n];\n{\n \"_id\":\"63a5bcc57433d072405cde86\",\n \"name\":\"Ali's Boxers\",\n \"description\":\"Boxers made specifically for ALi\",\n \"department\":\"6398fbf11fc0f2835e898aa8\",\n \"category\":\"6398fbfd1fc0f2835e898aae\",\n \"variations\":[\n \"63a5bcc57433d072405cde8d\",\n \"63a5bcc67433d072405cde95\"\n ],\n \"price\":50,\n \"discount\":0,\n \"identifier\":\"A\",\n \"createdAt\":\"2022-12-23T14:35:50.556Z\",\n \"updatedAt\":\"2022-12-23T14:35:50.556Z\",\n \"__v\":0\n}\n{\n \"_id\":\"63a5bcc57433d072405cde86\",\n \"name\":\"Ali's Boxers\",\n \"description\":\"Boxers made specifically for ALi\",\n \"department\":{\n \"_id\":\"6398fbf11fc0f2835e898aa8\",\n \"name\":\"male\",\n \"description\":\"male\",\n \"skuCode\":\"M\",\n \"createdAt\":\"2022-12-13T22:25:53.549Z\",\n \"updatedAt\":\"2022-12-13T22:25:53.549Z\",\n \"__v\":0\n },\n \"category\":{\n \"_id\":\"6398fbfd1fc0f2835e898aae\",\n \"name\":\"main\",\n \"title\":\"main\",\n \"description\":\"main\",\n \"skuCode\":\"M\",\n \"parent\":null,\n \"createdAt\":\"2022-12-13T22:26:05.996Z\",\n \"updatedAt\":\"2022-12-13T22:26:05.996Z\",\n \"__v\":0\n },\n \"variations\":[\n {\n \"_id\":\"63a5bcc57433d072405cde8d\",\n \"color\":{\n \"_id\":\"6398fbdb1fc0f2835e898a91\",\n \"name\":\"red\",\n \"code\":\"#d44a4a\",\n \"skuCode\":\"001\",\n \"createdAt\":\"2022-12-13T22:25:31.140Z\",\n \"updatedAt\":\"2022-12-14T08:26:36.023Z\",\n \"__v\":0\n },\n \"size\":{\n \"_id\":\"6398fbe61fc0f2835e898aa1\",\n \"name\":\"small\",\n \"skuCode\":\"Y\",\n \"createdAt\":\"2022-12-13T22:25:42.795Z\",\n \"updatedAt\":\"2022-12-13T22:25:42.795Z\",\n \"__v\":0\n },\n \"stock\":[\n {\n \"_id\":\"63a5bcc57433d072405cde89\",\n \"available\":2,\n \"reserved\":0,\n \"store\":0,\n \"labourCost\":{\n \"_id\":\"63a1deb1d5890e2103410bf4\",\n \"title\":\"Ali Boxers Maker\",\n \"description\":\"Ali needs his boxers hand made\",\n \"amount\":20,\n \"createdAt\":\"2022-12-20T16:11:29.690Z\",\n \"updatedAt\":\"2022-12-22T17:06:37.667Z\",\n \"__v\":0\n },\n \"materials\":[\n {\n \"amount\":1,\n \"material\":null,\n \"_id\":\"63a5bcc57433d072405cde8a\"\n },\n {\n \"amount\":1,\n \"material\":{\n \"_id\":\"639a251596ae4b5c1af788c0\",\n \"name\":\"mamam\",\n \"description\":\"2121\",\n \"stock\":121195,\n \"supplier\":\"test\",\n \"costPerUnit\":1,\n \"fabric\":\"polyester\",\n \"createdAt\":\"2022-12-14T19:33:41.047Z\",\n \"updatedAt\":\"2022-12-25T01:40:56.383Z\",\n \"__v\":0\n },\n \"_id\":\"63a5bcc57433d072405cde8b\"\n }\n ],\n \"createdAt\":\"2022-12-23T14:35:49.735Z\",\n \"updatedAt\":\"2022-12-23T14:58:06.156Z\",\n \"__v\":0\n }\n ],\n \"images\":{\n \"_id\":\"63a5bcc57433d072405cde87\",\n \"product\":\"63a5bcc57433d072405cde86\",\n \"color\":\"6398fbdb1fc0f2835e898a91\",\n \"images\":[\n {\n \"_id\":\"6375c3d97d5dc191a77ca7ac\",\n \"name\":\"boutiqueb-hahhaha-1668662233138.jpeg\",\n \"displayName\":\"hahhaha\",\n \"createdAt\":\"2022-11-17T05:17:13.159Z\",\n \"updatedAt\":\"2022-11-17T05:17:13.159Z\",\n \"__v\":0\n },\n {\n \"_id\":\"6375c40d7d5dc191a77ca7c2\",\n \"name\":\"boutiqueb-paypal-1668662285552.jpeg\",\n \"displayName\":\"paypal\",\n \"createdAt\":\"2022-11-17T05:18:05.570Z\",\n \"updatedAt\":\"2022-11-17T05:18:05.570Z\",\n \"__v\":0\n }\n ],\n \"createdAt\":\"2022-12-23T14:35:49.561Z\",\n \"updatedAt\":\"2022-12-23T14:35:49.561Z\",\n \"__v\":0\n },\n \"createdAt\":\"2022-12-23T14:35:49.897Z\",\n \"updatedAt\":\"2022-12-23T14:35:49.897Z\",\n \"__v\":0\n },\n {\n \"_id\":\"63a5bcc67433d072405cde95\",\n \"color\":{\n \"_id\":\"639b75a799cf2ed9eb2802ec\",\n \"name\":\"dr\",\n \"code\":\"#301313\",\n \"skuCode\":\"002\",\n \"createdAt\":\"2022-12-15T19:29:43.798Z\",\n \"updatedAt\":\"2022-12-15T19:29:43.798Z\",\n \"__v\":0\n },\n \"size\":{\n \"_id\":\"639b759899cf2ed9eb2802e4\",\n \"name\":\"medium\",\n \"skuCode\":\"Z\",\n \"createdAt\":\"2022-12-15T19:29:28.047Z\",\n \"updatedAt\":\"2022-12-15T19:29:28.047Z\",\n \"__v\":0\n },\n \"stock\":[\n {\n \"_id\":\"63a5bcc67433d072405cde91\",\n \"available\":2,\n \"reserved\":0,\n \"store\":0,\n \"labourCost\":{\n \"_id\":\"63a1deb1d5890e2103410bf4\",\n \"title\":\"Ali Boxers Maker\",\n \"description\":\"Ali needs his boxers hand made\",\n \"amount\":20,\n \"createdAt\":\"2022-12-20T16:11:29.690Z\",\n \"updatedAt\":\"2022-12-22T17:06:37.667Z\",\n \"__v\":0\n },\n \"materials\":[\n {\n \"amount\":1,\n \"material\":null,\n \"_id\":\"63a5bcc67433d072405cde92\"\n },\n {\n \"amount\":1,\n \"material\":{\n \"_id\":\"639a44fc5a053c1a05e60b44\",\n \"name\":\"test emile\",\n \"description\":\"test test\",\n \"stock\":2,\n \"supplier\":\"emile\",\n \"costPerUnit\":1,\n \"fabric\":\"cotton\",\n \"createdAt\":\"2022-12-14T21:49:48.322Z\",\n \"updatedAt\":\"2022-12-25T15:46:03.105Z\",\n \"__v\":0,\n \"image\":\"63a8703adb0f557f329cabfa\"\n },\n \"_id\":\"63a5bcc67433d072405cde93\"\n }\n ],\n \"createdAt\":\"2022-12-23T14:35:50.229Z\",\n \"updatedAt\":\"2022-12-23T14:35:50.229Z\",\n \"__v\":0\n }\n ],\n \"images\":{\n \"_id\":\"63a5bcc67433d072405cde8f\",\n \"product\":\"63a5bcc57433d072405cde86\",\n \"color\":\"639b75a799cf2ed9eb2802ec\",\n \"images\":[\n {\n \"_id\":\"6375c3d97d5dc191a77ca7ac\",\n \"name\":\"boutiqueb-hahhaha-1668662233138.jpeg\",\n \"displayName\":\"hahhaha\",\n \"createdAt\":\"2022-11-17T05:17:13.159Z\",\n \"updatedAt\":\"2022-11-17T05:17:13.159Z\",\n \"__v\":0\n },\n {\n \"_id\":\"6375c40d7d5dc191a77ca7c2\",\n \"name\":\"boutiqueb-paypal-1668662285552.jpeg\",\n \"displayName\":\"paypal\",\n \"createdAt\":\"2022-11-17T05:18:05.570Z\",\n \"updatedAt\":\"2022-11-17T05:18:05.570Z\",\n \"__v\":0\n }\n ],\n \"createdAt\":\"2022-12-23T14:35:50.067Z\",\n \"updatedAt\":\"2022-12-23T14:35:50.067Z\",\n \"__v\":0\n },\n \"createdAt\":\"2022-12-23T14:35:50.395Z\",\n \"updatedAt\":\"2022-12-23T14:35:50.395Z\",\n \"__v\":0\n }\n ],\n \"price\":50,\n \"discount\":0,\n \"identifier\":\"A\",\n \"createdAt\":\"2022-12-23T14:35:50.556Z\",\n \"updatedAt\":\"2022-12-23T14:35:50.556Z\",\n \"__v\":0\n}\n"}, {"role": "assistant", "content": "Text:your values in your documents are no longer a collection of ids after population. they now are objects with their own _id fields and you now need to query them accordingly.by the way, it is weird your id values seem to be stored as mere strings, not as $oid as you showed previously. are you using versioning in models and queries? try to get also another sample with __v:1 for example and see how they differ.one more thing about formatting your posts. they are long and makes it hard to follow when someone new comes in. from the icon in the editor, select \u201cHide Details\u201d and put your \u201ccode\u201d sections in it and edit the text it show to reflect the content. chek the below one for example.this way it will be easier to read when your sample code starts to be lengthy\nCode:_id$oid__v:1"}, {"role": "user", "content": "Text:it appears as $oid when I copy it from my document itself. But what I sent was the result of my findOne() and in this case it appears like that.department an category were working. I didn\u2019t need to add _id for it to work. In fact, when I tried it with them, it stopped working.As for color and size, it didn\u2019t work this way either.EDIT: I removed all versionKeys from my models, still didn\u2019t work.\nCode:$oidfindOne()_id"}, {"role": "assistant", "content": "Text:I might have a mistake as I failed to find my reference line about this: if you use \u201cexec\u201d, previous stages were first combined and then executed. I had the idea that documents are first populated and find operation was applied. I could even misunderstand that line. I will check this later on.anyways, for now, let\u2019s try to check your use of the code. unlike for color and size, you don\u2019t seem to convert any id field for department and category. so, how do you use your buildProductQuery function and what are the values of these variables: { department, category, color, size } = query (edit sensitive information)\nCode:buildProductQuery{ department, category, color, size } = query"}, {"role": "user", "content": "Text:department: 6398fbf11fc0f2835e898aa8\ncategory: 6398fbfd1fc0f2835e898aaeWhen I try to filter with any (or both) of the above, it\u2019s working perfectly.color: 639b75a799cf2ed9eb2802ec\nsize: 639b759899cf2ed9eb2802e4When I try to filter with any (or both) of the above, it\u2019s not working.\nHere is a query example for when I filter with color:\nCode:6398fbf11fc0f2835e898aa86398fbfd1fc0f2835e898aae639b75a799cf2ed9eb2802ec639b759899cf2ed9eb2802e4{\n variations: { '$ne': [] },\n 'variations.color': '639b75a799cf2ed9eb2802ec'\n}\n"}, {"role": "assistant", "content": "Text:to play with, I modified/minified your model, query, populate query, and data. I kept only id fields and a few keys such as names.It seems mongoose takes string representation of ObjectId as input and converts it internally depending on the model properties. for example the following query on variations collection gets correct color object then populates it.its output isthis explains why the department and category of your query work without manually converting them to ObjectId.as for the sub-fields, I found out that a matching query is possible by the populate method itself. the following link\nMongoose v6.8.1: Query (mongoosejs.com)here, I embed the match query for the color into the populate query:giving the following result:This means removing color and size from your buildProductQuery method and creating a new populate query builder to use them.I don\u2019t know if any other method exists but this seems pretty easy to implement.by the way, I don\u2019t know if it is mongoose or JSON.stringfy but I now can see why your sample data had strings in place of ObjectIds:\nCode:await Variation.find({\"color\":\"639b75a799cf2ed9eb2802ec\"}).populate(\"color\")\n[\n {\n _id: new ObjectId(\"63a5bcc67433d072405cde95\"),\n color: { _id: new ObjectId(\"639b75a799cf2ed9eb2802ec\"), name: 'dr' },\n size: new ObjectId(\"639b759899cf2ed9eb2802e4\")\n }\n]\nlet found = await Product.find()\n .populate({\n path: \"variations\",\n model: this.Variation,\n match:{ \"color\": \"639b75a799cf2ed9eb2802ec\" },\n populate: [\n {\n path: \"color\",\n model: this.Color,\n },\n {\n path: \"size\",\n model: this.Size,\n }\n ]\n })\n{\n \"_id\": \"63a5bcc57433d072405cde86\",\n \"name\": \"Ali's Boxers\",\n \"description\": \"Boxers made specifically for ALi\",\n \"department\": \"6398fbf11fc0f2835e898aa8\",\n \"category\": \"6398fbfd1fc0f2835e898aae\",\n \"variations\": [\n {\n \"_id\": \"63a5bcc67433d072405cde95\",\n \"color\": {\n \"_id\": \"639b75a799cf2ed9eb2802ec\",\n \"name\": \"dr\"\n },\n \"size\": {\n \"_id\": \"639b759899cf2ed9eb2802e4\",\n \"name\": \"medium\"\n }\n }\n ]\n}\nbuildProductQueryJSON.stringfy// actual object{\n _id: new ObjectId(\"63a5bcc57433d072405cde86\"),\n name: \"Ali's Boxers\",\n description: 'Boxers made specifically for ALi',\n department: new ObjectId(\"6398fbf11fc0f2835e898aa8\"),\n category: new ObjectId(\"6398fbfd1fc0f2835e898aae\"),\n variations: [\n new ObjectId(\"63a5bcc57433d072405cde8d\"),\n new ObjectId(\"63a5bcc67433d072405cde95\")\n ]\n}\n// JSON.stringify applied\n{\n \"_id\": \"63a5bcc57433d072405cde86\",\n \"name\": \"Ali's Boxers\",\n \"description\": \"Boxers made specifically for ALi\",\n \"department\": \"6398fbf11fc0f2835e898aa8\",\n \"category\": \"6398fbfd1fc0f2835e898aae\",\n \"variations\": [\"63a5bcc57433d072405cde8d\", \"63a5bcc67433d072405cde95\"]\n}\n"}, {"role": "user", "content": "Text:This means removing color and size from your buildProductQuery method and creating a new populate query builder to use them.I don\u2019t know if any other method exists but this seems pretty easy to implement.That seems like a good idea. However if a color is not found in a variations array, it will still return an empty array, which defies the whole point of variations: { $ne: [] } in my filters, and I do not with for this to happen.Moreover, I am using countDocuments(queryObj) to count how many items with a certain filter I have so I can create a pagination. Using your suggestedway kinda ruins it? Unless there is something I am missing.Here is my function, with the way you suggested, using buildProductPopulateQuery(req.query), in case you need to take a look:\nCode:buildProductQueryvariations: { $ne: [] }countDocuments(queryObj)buildProductPopulateQuery(req.query)exports.getAll = async (req, res) => {\n try {\n const { offset, limit } = req.query;\n const offsetInt = parseInt(offset) || 0;\n const limitInt = parseInt(limit) || 15;\n\n const queryObj = buildProductQuery(req.query);\n const populateQuery = buildProductPopulateQuery(req.query);\n\n console.log(JSON.stringify(populateQuery));\n\n const products = await Product.find(queryObj)\n .limit(limitInt)\n .skip(offsetInt)\n .populate(populateQuery);\n\n const totalProductsCount = await Product.countDocuments(queryObj);\n const totalPages = Math.ceil(totalProductsCount / limitInt);\n const currentPage = Math.ceil(offsetInt / limitInt) + 1;\n\n return Response.success(res, {\n products,\n pagination: {\n total: totalProductsCount,\n pages: totalPages,\n current: currentPage,\n },\n });\n } catch (err) {\n return Response.serverError(res, err.message);\n }\n};\n"}, {"role": "user", "content": "Text:Alright I figured out a way using aggregate()\nCode:aggregate()exports.getAll = async (req, res) => {\n\n try {\n\n const { offset, limit } = req.query;\n\n const offsetInt = parseInt(offset) || 0;\n\n const limitInt = parseInt(limit) || 15;\n\n const query = {\n\n departments: req.query.departments\n\n ? JSON.parse(req.query.departments)\n\n : null,\n\n categories: req.query.categories\n\n ? JSON.parse(req.query.categories)\n\n : null,\n\n colors: req.query.colors ? JSON.parse(req.query.colors) : null,\n\n sizes: req.query.sizes ? JSON.parse(req.query.sizes) : null,\n\n };\n\n const pipeline = buildProductPipeline(query);\n\n const countPipeline = buildCountProductPipeline(query);\n\n const products = await Product.aggregate(pipeline)\n\n .skip(offsetInt)\n\n .limit(limitInt);\n\n const totalProductsCount =\n\n (await Product.aggregate(countPipeline))[0]?.count || 0;\n\n const totalPages = Math.ceil(totalProductsCount / limitInt);\n\n const currentPage = Math.ceil(offsetInt / limitInt) + 1;\n\n return Response.success(res, {\n\n products,\n\n pagination: {\n\n total: totalProductsCount,\n\n pages: totalPages,\n\n current: currentPage,\n\n },\n\n });\n\n } catch (err) {\n\n return Response.serverError(res, err.message);\n\n }\n\n};\nconst buildProductPipeline = (query) => {\n const { departments, categories, colors, sizes } = query;\n\n return [\n {\n $match: {\n ...(departments && {\n department: {\n $in: departments.map((d) => mongoose.Types.ObjectId(d)),\n },\n }),\n ...(categories && {\n category: { $in: categories.map((c) => mongoose.Types.ObjectId(c)) },\n }),\n },\n },\n {\n $lookup: {\n from: \"variations\",\n localField: \"variations\",\n foreignField: \"_id\",\n as: \"variations\",\n pipeline: [\n {\n $match: {\n ...(colors && {\n color: {\n $in: colors.map((c) => mongoose.Types.ObjectId(c)),\n },\n }),\n ...(sizes && {\n size: {\n $in: sizes.map((s) => mongoose.Types.ObjectId(s)),\n },\n }),\n },\n },\n {\n $lookup: {\n from: \"colors\",\n localField: \"color\",\n foreignField: \"_id\",\n as: \"color\",\n },\n },\n {\n $unwind: {\n path: \"$color\",\n preserveNullAndEmptyArrays: true,\n },\n },\n {\n $lookup: {\n from: \"sizes\",\n localField: \"size\",\n foreignField: \"_id\",\n as: \"size\",\n },\n },\n {\n $unwind: {\n path: \"$size\",\n preserveNullAndEmptyArrays: true,\n },\n },\n {\n $lookup: {\n from: \"stocks\",\n localField: \"stock\",\n foreignField: \"_id\",\n as: \"stock\",\n pipeline: [\n {\n $lookup: {\n from: \"labourcosts\",\n localField: \"labourCost\",\n foreignField: \"_id\",\n as: \"labourCost\",\n },\n },\n {\n $unwind: {\n path: \"$labourCost\",\n preserveNullAndEmptyArrays: true,\n },\n },\n {\n $lookup: {\n from: \"materials\",\n as: \"materials\",\n pipeline: [\n {\n $lookup: {\n from: \"materials\",\n localField: \"material\",\n foreignField: \"_id\",\n as: \"material\",\n },\n },\n {\n $unwind: {\n path: \"$material\",\n preserveNullAndEmptyArrays: true,\n },\n },\n ],\n },\n },\n ],\n },\n },\n ],\n },\n },\n {\n $match: {\n variations: { $ne: [] },\n },\n },\n {\n $lookup: {\n from: \"departments\",\n localField: \"department\",\n foreignField: \"_id\",\n as: \"department\",\n },\n },\n {\n $unwind: {\n path: \"$department\",\n preserveNullAndEmptyArrays: true,\n },\n },\n {\n $lookup: {\n from: \"categories\",\n localField: \"category\",\n foreignField: \"_id\",\n as: \"category\",\n },\n },\n {\n $unwind: {\n path: \"$category\",\n preserveNullAndEmptyArrays: true,\n },\n },\n ];\n};\nconst buildCountProductPipeline = (query) => {\n const { departments, categories, colors, sizes } = query;\n\n return [\n {\n $match: {\n ...(departments && {\n department: {\n $in: departments.map((d) => mongoose.Types.ObjectId(d)),\n },\n }),\n ...(categories && {\n category: { $in: categories.map((c) => mongoose.Types.ObjectId(c)) },\n }),\n },\n },\n {\n $lookup: {\n from: \"variations\",\n localField: \"variations\",\n foreignField: \"_id\",\n as: \"variations\",\n },\n },\n {\n $match: {\n ...(colors && {\n \"variations.color\": {\n $in: colors.map((c) => mongoose.Types.ObjectId(c)),\n },\n }),\n ...(sizes && {\n \"variations.size\": {\n $in: sizes.map((s) => mongoose.Types.ObjectId(s)),\n },\n }),\n },\n },\n {\n $group: {\n _id: \"$_id\",\n count: { $sum: 1 },\n },\n },\n {\n $count: \"count\",\n },\n ];\n};\n"}, {"role": "assistant", "content": "Text:lingering references to non-existence variations are not good. this need for checking empty variations shows signs of bad design, either on the creation of a product or accessing the database outside the client app. if you have authority over the design you may consider refactoring your design.anyways, it seems you may have two occurrences where you will have an empty variations array. the array can be empty at creation (or later updated), and \u201cpopulate\u201d may result in an empty array. for the first one include variations: { $ne: [] } in \u201cbuildProductQuery\u201d and then use vanilla js filtering on the result for the second case:however, keep in mind that this works on the app\u2019s host\u2019s memory so use .lean() to reduce memory usage. And again, I still don\u2019t know if any other method exists. Until we find a better way (if any), this one handles the jobs pretty well.One way might be to leverage the $lookup of mongodb through Model.aggregate where you have more (or total) control over your query to run on the database, but you need to spend some time learning it as it gets complicated at times. you can also leverage the counting documents and creating pagination on the database server itself. the bad news is, I use aggregation, but I haven\u2019t used it with mongoose, so that beats me here.\nCode:variations: { $ne: [] } products = (await Product.find({\"variations\":{\"$ne\":[]}}).populate(\"variations\"))\n .filter(function (product) { return product[\"variations\"].length>0; })\n.lean()$lookupModel.aggregate"}, {"role": "user", "content": "Text:lingering references to non-existence variations are not good. this need for checking empty variations shows signs of bad design, either on the creation of a product or accessing the database outside the client app. if you have authority over the design you may consider refactoring your design.We do not want to delete a product if it has no variations, as the admins can always add new ones. what causes the variations to be empty is when they get archived and moved to the archive table. In that canse, we want the product to still be available so we reference to it by id.\nCode:{\n product: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Product\",\n required: true,\n },\n variation: {\n type: mongoose.Schema.Types.ObjectId,\n ref: \"Variation\",\n required: true,\n },\n}\n"}, {"role": "assistant", "content": "Text:I did not notice your second post came while I was writing you have a nice pipeline there. I don\u2019t know how mongoose glues \u201cmodels\u201d after using aggregation, but if it does the job let it do the job, and if so, then you should mark it as \u201cthe accepted answer\u201d so the community can see this problem is solved \nCode:"}, {"role": "user", "content": "Text:Went ahead and did just that.Thanks again for your help, really appreciate your time.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongoose Server selection Error and tags: ['node-js', 'mongoose-odm', 'connecting']"}, {"role": "user", "content": "Text:I have 4 VM where Docker containers are running for Node js services which are connecting with MongoDB which are running in a docker container on other 3 VM. when we deploy the service sometimes the only service from 1st VM get connected to mongo sometimes other VM NodeJs service shows the server selection error Shown in the image and all ports are allowed to connect internally within All 7 VM Mongo Version 4.2.8 Node j\nScreenshot 2021-07-02 at 3.54.38 PM1120\u00d7662 379 KB\ns Version 14.2.0 Mongoose Version 5.9.6\nCode:"}, {"role": "assistant", "content": "Text:me also can you help me in this error\nCode:"}, {"role": "assistant", "content": "Text:this worked for me:within your mongoDB atlas\u2026\nin Network Access\u2026 edit IP access list\nswitch it to \u201callow access from anywhere\u201d\nimage858\u00d7512 17.9 KB\n\nCode:"}, {"role": "assistant", "content": "Text:this worked for meIt did worked for you because you are connecting to an Atlas cluster. The other person is not using Atlas.\nCode:"}, {"role": "assistant", "content": "Text:replace local host with 127.0.0.1 it work every time\nCode:"}, {"role": "assistant", "content": "Text:thank you so much !!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Query Targeting: Scanned Objects / Returned has gone above 1000 and tags: ['monitoring']"}, {"role": "user", "content": "Text:Hello Team,Recently in our production environment we are getting the following alert \u201cQuery Targeting: Scanned Objects / Returned has gone above 1000\u201d continuously at least twice a week but when our team checks the profiler during the time of alert all the queries execution time was not more than 50ms and also all the queries which were running during the time of alert was insert queries.\nEven in performance advisor I didn\u2019t get any suggestion to add new index based on the generated alerts. Can you please help me with this since it is production platform we are worried about this alert\nCode:"}, {"role": "assistant", "content": "Text:Hi @Vignesh_Ramesh,Welcome to MongoDB community.I think the best for you to contact our Atlas support to look into your production specific workload.High query targeting usually indicate on suboptimal queries as more documents are scanned vs returned. However, if you don\u2019t see ant impact in actual performance this alert might not be critical for you and you may ignore it or tune the threshold to fit your monitoring needs.Thanks\nPavel\nCode:"}, {"role": "assistant", "content": "Text:How I can tune it so that it works properly? via indexing?\nCode:"}, {"role": "assistant", "content": "Text:@Chris_Heffernan Usually yes, but it depends on the specific env.Look into performance advisor to see if anything is suggested.\nCode:"}, {"role": "assistant", "content": "Text:Any ideas if index creation will send Query Targeting: Scanned Objects / Returned alert?Thanks!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to reference the objectId from one collection/schema to another? and tags: ['node-js', 'mongoose-odm']"}, {"role": "user", "content": "Text:Hello everybody,\nI have two schemas. The first looks as follows:The second looks as follows:You can interpret the TestRun as whole and the TestCases as subset of TestRun. When I\u2019m saving the testrun into the database into the testrun collection the testcases will also be saved into the testcases collection as own object per testcase.\nWhat I want to do is to add the objectId from the Testrun document into each testcase object or in other words I want to reference the objectId from the testrun to each testcase. Is it possible somehow?From what I read so far I thought something like this could do the work.But this didn\u2019t work.I\u2019m a absolute beginner, so maybe I\u2019m getting something totally wrong.Any help is really appreciated.Best regards\nCode:const TestRunSchema: Schema = new Schema(\n\n {\n\n testRun: {\n\n type: Array,\n\n testcases: [\n\n {\n\n name: { type: String },\n\n url: { type: String },\n\n devices: { type: [String] },\n\n userAgent: { type: String },\n\n viewport: {\n\n width: { type: Number },\n\n height: { type: Number }\n\n },\n\n isMobile: { type: Boolean },\n\n hasTouch: { type: Boolean },\n\n browser: { type: String },\n\n fullPage: { type: Boolean },\n\n element: {\n\n toScreenshot: { type: String },\n\n toClick: { type: String },\n\n toHover: { type: String }\n\n }\n\n }\n\n ]\n\n }\n\n },\n\n);\nconst TestCaseSchema: Schema = new Schema([\n\n {\n\n testrunId: {\n\n type: mongoose.Schema.Types.ObjectId,\n\n ref: 'TestRun'\n\n },\n\n name: String,\n\n url: String,\n\n devices: [{type: String}],\n\n userAgent: {type: String},\n\n viewport: {\n\n width: {type: Number},\n\n height: {type: Number}\n\n },\n\n isMobile: {type: Boolean},\n\n hasTouch: {type: Boolean},\n\n browser: {type: String},\n\n fullPage: {type: Boolean},\n\n element: {\n\n toScreenshot: {type: String},\n\n toClick: {type: String},\n\n toHover: {type: String}\n\n }\n\n },\n\n {\n\n versionKey: false\n\n }\n\n]);\ntestrunId: {\n\n type: mongoose.Schema.Types.ObjectId,\n\n ref: 'TestRun'\n\n },\n"}, {"role": "assistant", "content": "Text:Hello @CHH_N_A ,I notice you haven\u2019t had a response to this topic yet - were you able to find a solution?\nIf not, could you please confirm if my understanding of your use case is correct?You are trying to refer the objectId of documents of TestCases collection into documents of TestRun collection.\nIf this is correct then you can try using populate().Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, a plain object, multiple plain objects, or all objects returned from a query. Let\u2019s look at an example.In case you have any more queries regarding this, then please provide some sample documents and example scenario to discuss further.Regards,\nTarun\nCode:const mongoose = require('mongoose');\nconst { Schema } = mongoose;\n\nconst personSchema = Schema({\n _id: Schema.Types.ObjectId,\n name: String,\n age: Number,\n stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]\n});\n\nconst storySchema = Schema({\n author: { type: Schema.Types.ObjectId, ref: 'Person' },\n title: String,\n fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]\n});\n\nconst Story = mongoose.model('Story', storySchema);\nconst Person = mongoose.model('Person', personSchema);\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB Community 5.0.12 Illegal instruction (core dumped) ubuntu 20.04.5 LTS and tags: ['installation']"}, {"role": "user", "content": "Text:Hi there,I\u2019m trying to get MongoDB 5.0.12 running on ubuntu 20.04.5 LTS, but whenever I try to start the mongod service through systemctl, I get the below output.At first I was trying to get 6.0.3 running but this gave me the same result, which is why I decided to switch to 5.0.12, which I already have running on a different development oriented ubuntu 22.04 machine.\nReinstalling the OS and trying the installation again from scratch gives me the exact same result.Running mongod --config /etc/mongod.conf returns Illegal instruction (core dumped).\nRunning sudo mongod --config /etc/mongod.conf returns Illegal instruction.\nRunning sudo mongod --logpath ~/mongod.log returns Illegal instruction and does not create a log file.I\u2019m running out of ideas and could use some help \nCode:user@ubuntu:~$ sudo systemctl start mongod\nuser@ubuntu:~$ sudo systemctl status mongod\n\u25cf mongod.service - MongoDB Database Server\n Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)\n Active: failed (Result: core-dump) since Wed 2022-12-14 10:43:06 UTC; 4s ago\n Docs: https://docs.mongodb.org/manual\n Process: 6318 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=dumped, signal=ILL)\n Main PID: 6318 (code=dumped, signal=ILL)\n\nDec 14 10:43:05 ubuntu systemd[1]: Started MongoDB Database Server.\nDec 14 10:43:06 ubuntu systemd[1]: mongod.service: Main process exited, code=dumped, status=4/ILL\nDec 14 10:43:06 ubuntu systemd[1]: mongod.service: Failed with result 'core-dump'.\nmongod --config /etc/mongod.confIllegal instruction (core dumped)sudo mongod --config /etc/mongod.confIllegal instructionsudo mongod --logpath ~/mongod.logIllegal instruction"}, {"role": "assistant", "content": "Text:It is a know issue discussed at length. See Search results for 'status=4/ILL' - MongoDB Developer Community Forums\nCode:"}, {"role": "user", "content": "Text:Thanks for the reply, turns out (in my case at least) the server I was using had an older CPU which does not support the AVX instruction set required by MongoDB 5.0+.For future reference, see this list of CPU\u2019s which support AVX: Advanced Vector Extensions - Wikipedia\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Syntax Error: \"Missing semicolon\" and tags: ['mongodb-shell']"}, {"role": "user", "content": "Text:Im new to MongoDB. Just installed Mongo through hombrew successfully. When I try to run the most basic commands such as \u201cmongosh \u2013 version\u201d or \u201cmongo help\u201d I get hit with a \u201cMissing Semicolon\u201d syntax error.Im not sure what Im doing wrong.Also, Im getting a reference error: \u201cmongosh not defined\u201d when running \u201cmongosh -help\u201d\nCode:"}, {"role": "assistant", "content": "Text:Most likely you are at mongo prompt\nExit and run your command from os prompt\nCode:"}, {"role": "user", "content": "Text:So all \u201cmongosh\u201d commands I should be running from os prompt? And do i need to get out of the mongosh shell altogether?\nCode:"}, {"role": "assistant", "content": "Text:Hi @Ariel_Nurieli,Not all mongosh command needs to be executed from the OS prompt. The options of the mongosh can be executed from the OS prompt. You can see all the options after running mongosh --help.\nhelp.png1407\u00d7413 46.8 KB\nTo see all the mongosh options refer to this link: https://www.mongodb.com/docs/mongodb-shell/reference/options/#optionsAnd for all the methods of mongosh: https://www.mongodb.com/docs/mongodb-shell/reference/methods/I hope it helps! Please let us know if you have any further questionsThanks,\nKushagra\nCode:mongoshmongoshmongosh --helpmongoshmongosh"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: About date filter in Mongodb query and tags: []"}, {"role": "user", "content": "Text:Hi guys\nSo I have a data with a field \u201ccreatedDate\u201d type Date. I want to filter out documents from my DB based on documents creation Date. My exact target is to filter documents from a specific date to 2 years before the current date. How could I do this, please someone help.\n(Note :- I need query for mongoshell version 3.4.24, I have created working query for higher versions already)\nCode:"}, {"role": "assistant", "content": "Text:need query for mongoshell version 3.4.24I have created working query for higher versions alreadyI do not see at first what would be the difference. Share the query you have and explain how it fails to provide the desired output.\nCode:"}, {"role": "user", "content": "Text:db.getCollection().deleteMany({ \"createdDate\": {\n $gt: ISODate(\"2020-12-31\"),\n $lte: new Date(ISODate().getTime() - 1000*86400*365*2)\n }})\nCode:db.getCollection().deleteMany({ \"createdDate\": { $gt: ISODate(\"2020-12-31\"), $lte: new Date(ISODate().getTime() - 1000*86400*365*2) }})"}, {"role": "user", "content": "Text:Read it as Mongodb server version 3.4.24\n(Not sure if shell or server need to be the same version or not)\nCode:"}, {"role": "assistant", "content": "Text:The query seems to be syntactically correct, but logically it is another story.Two years before today is 2020-12-10, as such no dates can be both $gt:2020-12-31 and $lte:2020-12-10.Check your math andexplain how it fails to provide the desired output.\nCode:"}, {"role": "user", "content": "Text:Actually, that will be in use from 2023 thats why written that way\nYou can change the dates and check. It is giving errors, I don\u2019t know why\nSome people said it could be a version issue, maybe the line written for $lte is not valid in 3.4.24\nCode:"}, {"role": "assistant", "content": "Text:I do not have 3.4. What is the error you get? Cut-n-paste the whole error message and/or stack trace.\nCode:"}, {"role": "user", "content": "Text:Failed to retrieve documentsDatabase error!\nStacktrace:\n|/ java.lang.Exception: [.[replica set] [direct]] Database error!\n|/ Mongo Server error (MongoQueryException): Query failed with error code 2 with name \u2018BadValue\u2019 and error message 'error processing query: ns=. batchSize=50Tree: $and\n|\u2026 createdDate $lte new Date(1668206779750)\n|\u2026 createdDate $gt new Date(1656633600000)\n|\u2026 Sort: {}\n|\u2026 Proj: {}\n|_\u2026 No query solutions\u2019 on server .\nCode:"}, {"role": "user", "content": "Text:One more point to be noted is:- when I cloned that collection locally and ran the query on it, it works but not on the actual remote one which is 3.4.24\nMakes me think it is a version issue only\nCode:"}, {"role": "assistant", "content": "Text:The error message really contains the strings , or you hiding the real name. I find it strange that the error message is not more detailed like it could show the real Database_Name and collection_name rather than place holder.| \u2026 Sort: {}\n| \u2026 Proj: {}This seems to indicate that the query you run in real like has more to it than the find you share. May the error lies in the part you did not share.\nCode:"}, {"role": "user", "content": "Text:Yes, I hide the actual database name and collection name because it is elated to my organization. Hope you dont mind\nRest I have shown the complete error\nCode:"}, {"role": "user", "content": "Text:Same goes for and \nBTW just the diff between the query I shared with you and the one I used to get this error is\nI used diff dates and used find instead of deleteMany because I didn\u2019t wanted to delete the data myself accidentally, just wanted to test the query\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Find multiple ids in collection (one line query) and tags: ['node-js']"}, {"role": "user", "content": "Text:*name is uniquecollection : {\n[{\n_id: \u20181\u2019,\nname: \u201cBob\u201d,\n},\n{\n_id: \u20182\u2019,\nname: \u201csara\u201d,\n},\n{\n_id: \u20183\u2019,\nname: \u201cjon\u201d,\n},\n],\n}\narrayToFind = [\u201cBob\u201d,\u201csara\u201d]need to find all matching names in one call.expected result => {\n_id: \u20181\u2019,\nname: \u201cBob\u201d,\n},\n{\n_id: \u20182\u2019,\nname: \u201csara\u201d,\n},\nCode:"}, {"role": "assistant", "content": "Text:Please enjoy the fine documentation of $in.\nCode:"}, {"role": "user", "content": "Text:$in returns only one doc and not all of them\nCode:"}, {"role": "assistant", "content": "Text:$in returns only one docIn does not. See the many examples in from the documentation.Or this one:\nCode:mongosh> c.find()\n{ _id: '1', name: 'Bob' }\n{ _id: '2', name: 'sara' }\n{ _id: '3', name: 'jon' }\nmongosh> arrayToFind = [ \"Bob\" , \"sara\" ]\nmongosh> c.find( { \"name\" : { \"$in\" : arrayToFind } } )\n{ _id: '1', name: 'Bob' }\n{ _id: '2', name: 'sara' }\n"}, {"role": "user", "content": "Text:thanks I find the bug in my code\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted and tags: ['node-js', 'mongoose-odm', 'connecting', 'atlas-cluster', 'server']"}, {"role": "user", "content": "Text:I keep getting this error although I have allowed access from anywhere in the Network access section of the cluster. (Screenshot of the same is attached below)\n\nimage1672\u00d7603 19.2 KB\nhere is the connection code**And the entire code is here https://replit.com/@KumaraswamyA/store-cipher-backend-1**(store-cipher-backend-1 - Replit)\nCode:`const mongoose = require('mongoose');\nconst mySecret = process.env['mongoUrl']\nconst intialDbConnection = async () => {\n try {\n await mongoose.connect(mySecret, {\n useNewUrlParser: true,\n useUnifiedTopology: true\n })\n console.log(\"db connected\")\n \n }\n catch (error) {\n console.error(error);\n }\n}\n\nmodule.exports = { intialDbConnection }`\nMongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/\n at NativeConnection.Connection.openUri (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/connection.js:824:32)\n at /home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:380:10\n at /home/runner/store-cipher-backend-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5\n at new Promise ()\n at promiseOrCallback (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)\n at Mongoose._promiseOrCallback (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:1225:10)\n at Mongoose.connect (/home/runner/store-cipher-backend-1/node_modules/mongoose/lib/index.js:379:20)\n at intialDbConnection (/home/runner/store-cipher-backend-1/db/db.connect.js:5:20)\n at Object. (/home/runner/store-cipher-backend-1/index.js:15:1) {\n reason: TopologyDescription {\n type: 'ReplicaSetNoPrimary',\n servers: Map(3) {\n 'cluster0-shard-00-00.fkvic.mongodb.net:27017' => [ServerDescription],\n 'cluster0-shard-00-01.fkvic.mongodb.net:27017' => [ServerDescription],\n 'cluster0-shard-00-02.fkvic.mongodb.net:27017' => [ServerDescription]\n },\n stale: false,\n compatible: true,\n heartbeatFrequencyMS: 10000,\n localThresholdMS: 15,\n setName: 'atlas-on2j4f-shard-0',\n logicalSessionTimeoutMinutes: undefined\n },\n code: undefined\n}\n"}, {"role": "assistant", "content": "Text:What do you get when you try to go at:\nCode:http://portquiz.net:27017/\n"}, {"role": "user", "content": "Text:This server listens on all TCP ports, allowing you to test any outbound TCP port.You have reached this page on port 27017 (from http host header).Your network allows you to use this port. (Assuming that your network is not doing advanced traffic filtering.)Network service: unknown\nYour outgoing IP: 59.91.26.158\nCode:"}, {"role": "assistant", "content": "Text:You have reached this page on port 27017 (from http host header).did you do this from replit console or your pc? where do you run your app? replit, work pc or home pc?I have tried and replit has no problem connecting Atlas clusters.One possibility is that you just haven\u2019t waited long enough when you added \u201c0.0.0.0\u201d to your network list. for me, it took about 15-20 seconds for the change to take effect.\nCode:"}, {"role": "user", "content": "Text:\nCode:"}, {"role": "assistant", "content": "Text:backend is in replitis that free or powered? free repls are stopped when you left the page or after a while.or ports got a problem somehow. try this on repl\u2019s \u201cshell\u201d: curl http://portquiz.net:27017/it should show \u201cPort test successful!\u201d and give the IP of that repl. try running your backend after this test and see if it connects.edit: do this also when you get that error and see if the port test succeeds.\nCode:curl http://portquiz.net:27017/"}, {"role": "user", "content": "Text:do this also when you get that error and see if the port test succeeds\nCode:"}, {"role": "assistant", "content": "Text:Today, I could finally get the same problem you are experiencing.Then, I did a side-by-side test with replit and Compass. Removing and re-adding the access from everywhere. Compass had no problem connecting.It seems the problem arises from the container (virtual machine) our repl is started. I got two different addressses that both succeeded portquiz.net test but one failed to connect mongodb:23.251.145.77 \u2192 Failed\n35.203.153.221 \u2192 ConnectedI have sent a bug report within the repl. I can\u2019t say what happens next. I suggest you close/reopen the repl by going back to \u201cMy Repls\u201d page, waiting a bit, and re-open it. check if you connect. if not, try again.\nCode:"}, {"role": "assistant", "content": "Text:Struggling for 2 days with the same connection issue. Tried suggested test methods and all of them are passed however still receiving error from mongodb.\nWaiting for a solution impatiently (my certification got stuck halfway).\nCode:"}, {"role": "assistant", "content": "Text:Struggling for 2 days with the same connection issue. Tried suggested test methods and all of them are passed however still receiving error from mongodb.Hi @Valikhan_Dumshebayev, Although the error is generic, the problem here turned out to be related to replit.com container. If your case is also related to a repl, please read my post just above yours. Else read on.The root of the problem is the strict access rules on the host network your app runs. You might be behind a strict school/work network that prevents certain connections to the internet. In these cases, you need to move to a more permissive network such as home or mobile.PS: It is still a mystery to me why we can connect to portquiz.net but not to mongodb servers.\nCode:"}, {"role": "assistant", "content": "Text:I am on my home network with no restriction. Actually, for me it has started at Saturday, then all of a sudden it got connected on Monday for some time and get disconnected again. Didn\u2019t check on Sunday, though.\nCode:"}, {"role": "assistant", "content": "Text:Actually, for me it has started at Saturday, then all of a sudden it got connected on Monday for some time and get disconnected againCan you please make a new post, include the full error message you get, and include a link here (because of irregularities)? That will allow both us community helpers and the mongodb staff to look with fresh sight.\nCode:"}, {"role": "assistant", "content": "Text:Sure.\nNo connection to MongoDB from Replit - MongoDB Atlas - MongoDB Developer Community Forums\nCode:"}, {"role": "user", "content": "Text:I can\u2019t say what happens next. I suggest you close/reopen the repl by going back to \u201cMy Repls\u201d page, waiting a bit, and re-open it. check if you connect. if not, try again.I have been doing this and sometimes it just doesn\u2019t work.\nCode:"}, {"role": "assistant", "content": "Text:I have been doing this and sometimes it just doesn\u2019t work.I know it is a pain to get a working container just continue with your luck.Please also consider sending a bug report from within the repl (help button on bottom-left) about this problem so to make replit team aware of the situation.\nCode:"}, {"role": "user", "content": "Text:Yep. I just did that.\nThanks for taking the time and helping me out. \nI will update you once the issue gets resolved.\nCode:"}, {"role": "user", "content": "Text:If you are following this thread, here is the temporary solution provided by replit support team.\u201cYou can run \u201ckill 1\u201d in the shell of your Repl which will reboot it and may fix the issue, although it isn\u2019t a 100% reliable workaround.\u201dApart from this the solution that has worked for me is changing the file name and running, the DB gets connected. In case you have already used the APIs in the frontend, after doing the above step change back your file name to the old one and the DB gets connected without any issues.Cheers.\nCode:"}, {"role": "assistant", "content": "Text:Apart from this the solution that has worked for me is changing the file name and running, the DB gets connectedthat is a weird one.\nCode:"}, {"role": "user", "content": "Text:maybe the repl becomes active with different IP when we change the repl file name.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Command insert requires authentication when connecting to remote server of database | code: 13, codeName: Unauthorized and tags: ['queries', 'node-js', 'mongoose-odm', 'api']"}, {"role": "user", "content": "Text:I\u2019m able to connect to the remote serverNow after calling API from software or postman I\u2019m getting below errorI\u2019ve tried below combinations for mongoDB connectionsSo please respond if you found any answers\nCode:const express =require(\"express\");\nconst bodyParser = require(\"body-parser\");\nconst mongoose = require(\"mongoose\");\nconst Promise = require('bluebird');\nPromise.promisifyAll(mongoose);\n\nconst app = express();\n\nmongoose.connect(\"mongodb://:@:/user\")\n .then(function(){\n console.log(\"Connected to database\");\n })\n .catch(function(err){\n console.log(\"Connection failed\", err);\n });\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({extended: true}));\napp.use(express.static(\"public\"));\n\n\n// Below is the schema and the database model\n\nconst userSchema = new mongoose.Schema({\n\n role_id: {type:Number},\n name:{ firstName:{type:String},\n middleName: {type:String},\n lastName: {type:String}\n },\n contact:{\n mobileNo:{type:Number},\n mail_id:{ \n username:{type:String},\n password:{type:String}\n }\n },\n address: {type:String},\n pincode: {type:Number},\n city: {type:String},\n state: {type:String}\n \n});\n\nconst User = mongoose.model(\"users\",userSchema);\n\n// Below is the get,post method\n\napp.get(\"/getusers\",function(req,res){\n User.find(function(err,foundUsers){ \n if(err){\n res.send(err);\n } else {\n res.send(foundUsers);\n }\n });\n});\n\napp.post(\"/getusers\",function(req,res){\n try {\n const newUser = new User({\n role_id: req.body.role_id ,\n name:{\n firstName: req.body.name.firstName,\n middleName: req.body.name.middleName,\n lastName: req.body.name.lastName\n },\n contact:{\n mobileNo: req.body.contact.mobileNo,\n mail_id:{\n username: req.body.contact.mail_id.username,\n password: req.body.contact.mail_id.password\n }\n },\n address: req.body.address,\n pincode: req.body.pincode,\n city: req.body.city,\n state: req.body.state\n });\n newUser.save();\n \n } catch (error) {\n console.log(error);\n }\n})\n/Documents/mProject/node_modules/mongodb/lib/cmap/connection.js:207\n callback(new error_1.MongoServerError(document));\n ^\n\nMongoServerError: command insert requires authentication\n at Connection.onMessage (/Documents/mProject/node_modules/mongodb/lib/cmap/connection.js:207:30)\n at MessageStream. (/Documents/mProject/node_modules/mongodb/lib/cmap/connection.js:60:60)\n at MessageStream.emit (node:events:513:28)\n at processIncomingData (/Documents/mProject/node_modules/mongodb/lib/cmap/message_stream.js:132:20)\n at MessageStream._write (/Documents/mProject/node_modules/mongodb/lib/cmap/message_stream.js:33:9)\n at writeOrBuffer (node:internal/streams/writable:391:12)\n at _write (node:internal/streams/writable:332:10)\n at MessageStream.Writable.write (node:internal/streams/writable:336:10)\n at Socket.ondata (node:internal/streams/readable:754:22)\n at Socket.emit (node:events:513:28)\n at addChunk (node:internal/streams/readable:315:12)\n at readableAddChunk (node:internal/streams/readable:289:9)\n at Socket.Readable.push (node:internal/streams/readable:228:10)\n at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {\n ok: 0,\n code: 13,\n codeName: 'Unauthorized',\n [Symbol(errorLabels)]: Set(0) {}\n}\n"}, {"role": "assistant", "content": "Text:Hi @R_V - Welcome to the communityI\u2019ve tried below combinations for mongoDB connections\nmongoose.connect(\u201cmongodb://${Username}:${Password}@${RemoteHost}:${Port}/user\u201d)\nmongoose.connect(\u201cmongodb://${RemoteHost}:${Port}/user\u201d)\nmongoose.connect(\u201cmongodb://${RemoteHost}/user\u201d)\nmongoose.connect(\u201cmongodb://${Username}:${Password}@${RemoteHost}/user\u201d)\nmongoose.connect(\u201cmongodb+srv://${Username}:${Password}@${RemoteHost}:${Port}/user\u201d)\nmongoose.connect(\u201cmongodb+srv://${RemoteHost}:${Port}/user\u201d)\nmongoose.connect(\u201cmongodb+srv://${RemoteHost}/user\u201d)\nmongoose.connect(\u201cmongodb+srv://${Username}:${Password}@${RemoteHost}/user\u201d)I do not believe this is due to the above combinations of connection strings used. The unauthorized error generally indicates that the associated database user does not have sufficient privileges to perform a particular action. You may find the following Built-In Roles documentation useful as a reference point.Regards,\nJason\nCode: codeName: 'Unauthorized',\nunauthorized"}, {"role": "user", "content": "Text:Thank you for the solution. It did helped.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Error parsing command line options and tags: ['atlas-cluster', 'database-tools', 'backup']"}, {"role": "user", "content": "Text:Hi guys,I am trying to clone a database using mongodump and mongorestore, however, when specifying the connection string I constantly receive the following error:\nimage1161\u00d748 3.2 KB\nI specify it the following way:mongodump --uri = \u2018mongodb+srv://:@cluster0.mv5da.mongodb.net/?retryWrites=true&w=majority\u2019If I use the same connection string to connect mongoshell it does work.Can somebody help me out?\nCode:"}, {"role": "assistant", "content": "Text:Try without extra spaces between the parameter name, the equal sign and the parameter value.\nCode:"}, {"role": "assistant", "content": "Text:Doesn\u2019t work. I came here with the same problem.I hate technology.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: I can't start mongodb server, because it status=2/INVALIDARGUMENT and tags: ['server', 'installation']"}, {"role": "user", "content": "Text:\nindex1057\u00d7335 75.9 KB\n\nCode:"}, {"role": "assistant", "content": "Text:What is your os?\nWhat command you used to start the service?\nCode:"}, {"role": "user", "content": "Text:Hi! My OS is Ubuntu.\nI used these commands to install Mongo 4.4wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -\necho \u201cdeb [ arch=amd64,arm64 ] MongoDB Repositories focal/mongodb-org/4.4 multiverse\u201d | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list\nsudo apt-get update\nsudo apt-get install mongodb-org=4.4.8 mongodb-org-server=4.4.8 mongodb-org-shell=4.4.8 mongodb-org-mongos=4.4.8 mongodb-org-tools=4.4.8\nsystemctl start mongod\nsystemctl enable mongod\nsystemctl status mongod\nCode:"}, {"role": "assistant", "content": "Text:I suspect two things for now:try running mongod --logpath ~/mongocrashes.log in the terminal. it should give a better log so we can examine it. use \u201cupload\u201d button in your answer and attach it.\nCode:mongod --logpath ~/mongocrashes.log"}, {"role": "assistant", "content": "Text:The error message isUsually the configuration file is /etc/mongodb.conf but since it could be different you can verify the actual name used by the service using:What ever is the file specified by -f or \u2013config, that file needs to exist and be readable by the user specified in the service file. You may find the user with:Next time you publish logs, screens output or code, please doing using the formatting specified in Formatting code and log snippets in posts. This way we can cut-n-paste in our reply or experimentation rather than typing over.\nCode:Error reading config file: No such file or directory\nsystemctl cat mongodb | grep ExecStart\nsystemctl cat mongodb | grep User\n"}, {"role": "assistant", "content": "Text:I suspect since sudo is not used with systemctl command it is unable to start mongod(not able to read mongod.conf file)\nCode:"}, {"role": "assistant", "content": "Text:That could be the case but my understanding a little bit different.The configuration file is read by mongod, not by systemctl. The process mongod is started as the User specified in the service file, so only this user needs to have read access to the file.But I will test your sudo theory once I am on my linux machine.\nCode:"}, {"role": "assistant", "content": "Text:Here comes the result.My bash prompt is: steevej ;So even if only mongodb user has read access systemctl still starts correctly. As a note, when I do systemctl start|stop without sudo, I have a dialog that ask for my passwd. So it looks like systemctl does a sudo behind the scene.More over, if I change the owner of /etc/mongodb.conf so that user mongodb does not have read access, it fails to start with the error Error opening config file: Permission denied.If I remove the configuration, it fails with Error opening config file \u2018/etc/mongodb.conf\u2019: No such file or directory. The error message is a little bit more explicit but I am using a more recent version:So the only conclusion I can make is that the configuration file does not exist.\nCode:: steevej ; systemctl status mongodb\n: steevej ; systemctl cat mongodb | grep ExecStart\n: steevej ; systemctl cat mongodb | grep User\n: steevej ; ls -l /etc/mongodb.conf\n: steevej ; systemctl start mongodb\n: steevej ; systemctl status mongodb\n\n\n: steevej ; systemctl status mongodb\n\u25cb mongodb.service - MongoDB Database Server\n Loaded: loaded (/usr/lib/systemd/system/mongodb.service; disabled; preset: disabled)\n Active: inactive (dead)\n Docs: https://docs.mongodb.org/manual\n\nNov 25 08:55:36 xps13 systemd[1]: Started MongoDB Database Server.\nNov 25 08:58:10 xps13 systemd[1]: Stopping MongoDB Database Server...\nNov 25 08:58:10 xps13 systemd[1]: mongodb.service: Deactivated successfully.\nNov 25 08:58:10 xps13 systemd[1]: Stopped MongoDB Database Server.\nNov 25 08:58:10 xps13 systemd[1]: mongodb.service: Consumed 2.309s CPU time.\n\n: steevej ; systemctl cat mongodb | grep ExecStart\nExecStart=/usr/bin/mongod --config /etc/mongodb.conf\n\n: steevej ; systemctl cat mongodb | grep User\nUser=mongodb\n\n: steevej ; ls -l /etc/mongodb.conf\n-rw------- 1 mongodb mongodb 678 Jul 13 10:42 /etc/mongodb.conf\n\n: steevej ; systemctl start mongodb\n\u25cf mongodb.service - MongoDB Database Server\n Loaded: loaded (/usr/lib/systemd/system/mongodb.service; disabled; preset: disabled)\n Active: active (running) since Fri 2022-11-25 09:00:46 EST; 40ms ago\n Docs: https://docs.mongodb.org/manual\n Main PID: 192273 (mongod)\n Memory: 2.0M\n CPU: 23ms\n CGroup: /system.slice/mongodb.service\n \u2514\u2500192273 /usr/bin/mongod --config /etc/mongodb.conf\n\nNov 25 09:00:46 xps13 systemd[1]: Started MongoDB Database Server.\n: steevej ; mongod --version\ndb version v5.0.3\n"}, {"role": "assistant", "content": "Text:@Mari_Mikhaleva , above command is the crucial part we need from your side. can you please provide us its output.\nCode:systemctl cat mongodb | grep ExecStart\n"}, {"role": "assistant", "content": "Text:mongod.conf.txt (667 Bytes)here is the default config file you can use. if you somehow deleted your config file, copy this one. but remember, you will still need the path we were asking for.or, put this file where ever you want (and accessible by systemctl) and edit the following line in /usr/lib/systemd/system/mongod.service (at least ubuntu 20 uses this path)\nCode:/usr/lib/systemd/system/mongod.serviceExecStart=/usr/bin/mongod --config /etc/mongod.conf"}, {"role": "user", "content": "Text:This is my file mongocrashes.log\nmongocrashes.log (1.2 KB)\nCode:"}, {"role": "assistant", "content": "Text:the file itself gives an error. edit your last post, rename the file to have txt extension, and upload/attach again.\nCode:txt"}, {"role": "user", "content": "Text:docs.txt (1.3 KB)\nCode:"}, {"role": "assistant", "content": "Text:Attempted to create a lock file on a read-only directory: /data/dbthis one is now related to folder permissions over /data/db. I am not a Linux guru, so please check how you give write access to mongod process.assuming it is your personal computer, just for the moment, give full access to it with sudo chmod 777 /data/db so we can see if you get any more errors.\nCode:/data/dbmongodsudo chmod 777 /data/db"}, {"role": "user", "content": "Text:This is a output of command:ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf\nCode:"}, {"role": "assistant", "content": "Text:I am guessing you corrected config file issue because your new log file says you don\u2019t have write permission for the path to store database files. please check my above post and share again if you still have errors.\nCode:"}, {"role": "assistant", "content": "Text:hi again @Mari_Mikhaleva, forum posts behave a bit strangely about sending new posts. sometimes just gives notifications, sometimes sends posts in an email. your last one (the one you seems deleted) came in an email, and I checked the log file.Initializing full-time diagnostic data capture with directory \u2018/data/db/diagnostic.data\u2019\nwaiting for connections on port 27017this means your config file is now fine and the data folder has the correct permissions so that the server is good to go. it is something nice to see.with that in hand, if you decide to reinstall mongodb you have now a way to check a few possible locations.Good Luck \nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Webhook / HTTPS Endpoint - error returned from Postman \"no authentication methods were specified\" and tags: []"}, {"role": "user", "content": "Text:Problem setting up a Webhook / HTTPS EndpointFollowing along with this video (which, despite being created this year, is apparently really out of date \u2013 application is seemingly undergoing massive change):Learn how to create a data api with MongoDB Atlas in 10 minutes or lessAt the 7:00 mark, Michael Lynn describes the settings for setting up a \u201c3rd party service\u201d (or \u201cwebhook\u201d) (now apparently known as \u201cHTTPS Endpoints\u201d) - specifically, choosing an authentication method (Application | System | UserId | Script).I am configuring my own HTTPS Endpoint, and nowhere am I given the option to configure this.when I try to test via Postman, I get the errorI thought maybe I had missing config within Realm - and found that I had no auth providers enabled. I enabled and deployed \u201cAPI Keys\u201d, then created an API key\u2026I am trying to post form data to that endpoint. In Postman, I am:\u2026but I get the same error.Any thoughts? Thank you!\nCode:{\n \"error\": \"no authentication methods were specified\",\n \"error_code\": \"InvalidParameter\",\n \"link\": \"https://realm.mongodb.com/groups/...[truncated]\n}\n"}, {"role": "assistant", "content": "Text:@Greg_Hammond ,It sounds like the webhook definition is set of \u201capplication authentication\u201d on the webhook definition. This method requires to provide at least one of your enabled authentication methods when calling the weebhook (for example a user/password via HTTP basic authetntication).The API KEY requires you to specify a specific field either in the body or header of the call and its not x-api-key but :If you do not need auth for the webhook you must set the authentication method to \u201cSYSTEM\u201d. Like in the tutorial :\n\nimage1533\u00d7789 54.7 KB\nBest regards,\nPavel\nCode:x-api-key{\n \"api-key\": \"\"\n}\n"}, {"role": "user", "content": "Text:Thank you Pavel, I really appreciate the response. Changing the auth field from \u2018x-api-key\u2019 to \u2018api-key\u2019 in the header worked for me.Apparently my endpoint was indeed configured to \u201capplication authentication\u201d, as sending the api-key worked. Again, though, the current UI for configuring this stuff doesn\u2019t even show me the Authentication section (as it does in the tutorial) \u2013 so I have no way of changing that setting, or even knowing what it is. Is that currently on a dev list?Thanks again,\nGreg\nCode:"}, {"role": "user", "content": "Text:Going to answer my own question here, for others\u2019 benefit:The authentication method is exposed on the Settings tab within Edit Function. This is also where the \u201cCan Evaluate\u201d JSON expression can be specified.Sorry for the confusion, hopefully this helps others going forward.Greg\nCode:"}, {"role": "assistant", "content": "Text:Greg, you\u2019re an amazing guy, and I wish you nothing but happiness in life.This small hidden setting had me searching for about 1.5 hours, and I thought my saving grace would be finding that video that was only 10 months old.Thank you so much for helping me find this setting, and understanding that was the reason why my API wasn\u2019t working.Also, thanks so much for coming back to post the update even after you found the resolution yourself.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Greg_Hammond and @SPat ,I see the confusion and I will highlight this UI change that might confuse users for improvement.Thanks for sharing your experience.Pavel\nCode:"}, {"role": "assistant", "content": "Text:Hi @Pavel_DuchovnyI\u2019m getting the same errorand I use email/password authentication and yes my function auth is ** application authentication**\nwhen I do http request from web browser using axios, I get that error, though I have passed the auth headerI think it should work if I use the realm-web SDK but I wanna use it with axios, in case I need to change the backend provider later.\nCode:no authentication methods were specified\nAuthorization: `Bearer ${_accessToken}`,\n"}, {"role": "assistant", "content": "Text:HI @Mohammed_Ramadan,For more details on other authentication providers (i.e, email/password and jwt token), you can follow our documentation found here. As the documentation is for our deprecated 3rd party service, please bear in mind that this is only temporary and we will also include a similar outline in the new HTTPS endpoint documentation.JWT TokenEmail / PasswordI hope this clears things up.Cheers,\nGiuliano\nCode:curl --location --request POST 'XXX' \\\n--header \"Content-Type: application/json\" \\\n--header \"jwtTokenString: \"\ncurl --location --request POST 'XXX' \\\n--header \"Content-Type: application/json\" \\\n--data '{\"username\": \"XXX\", \"password\": \"XXX\"}'\n"}, {"role": "assistant", "content": "Text:Hi @giulianocelani ,Thank you for your comment. But I have tried the email/password approach and it didn\u2019t work plus I want to access the app through HTTPS endpoint and not the CLI.\nCode:"}, {"role": "assistant", "content": "Text:This is super useful. Thanks for solving. I\u2019m new to MongoDB and working with backend data. The guides and documents from MongoDB are not very useful and quite confusing as there\u2019s lots of assumed knowledge.Even where to select Authentication Option of System is not very intuitive where you can only change it by selecting the word within your HTTPS endpoint \u201cLinked Function\u201d to go to the right section where this option is enabled.We are there though, thanks again all!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Timeout when selecting a server after inactivity and tags: ['dot-net', 'replication', 'compass', 'connecting', 'atlas-cluster']"}, {"role": "user", "content": "Text:Hi,We are using mongodb atlas using a mongodb+srv connection. When our webapp is starting up and handling requests - everything is working just fine. When our webapp gets inactive/idle a few hours we a getting timeouts on new requests:We are using MongoDB.Driver version 2.14.1.The heartbeats are also running just fine, even tough the app reports the timeouts:Meanwhile the app is reporting timeouts, we can;but we can only get the webapp running again by restarting it.We have 3 different test environments, they all having the same problem.Any suggestions, or know ways of doing further diagnostics?\nCode:mongodb+srvSystem.TimeoutException: A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : \"1\", ConnectionMode : \"ReplicaSet\", Type : \"ReplicaSet\", State : \"Disconnected\", Servers : [] }. \nat MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException(IServerSelector selector, ClusterDescription description) \nat MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedHelper.HandleCompletedTask(Task completedTask) \nat MongoDB.Driver.Core.Clusters.Cluster.WaitForDescriptionChangedAsync(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken) \nat MongoDB.Driver.Core.Clusters.Cluster.SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken) \nat MongoDB.Driver.MongoClient.AreSessionsSupportedAfterServerSelectionAsync(CancellationToken cancellationToken) \nat MongoDB.Driver.MongoClient.AreSessionsSupportedAsync(CancellationToken cancellationToken) \nat MongoDB.Driver.MongoClient.StartImplicitSessionAsync(CancellationToken cancellationToken) \nat MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)\nMongoDB.DriverMongoDB-SDAM Verbose: 405 : connection[1:xxxxxxxxx-dev-shard-00-02.yyyy.mongodb.net:27017:6-155102]: sent heartbeat in 60059.3808ms.\n DateTime=2022-02-17T14:48:01.0366223Z\nMongoDB-SDAM Verbose: 404 : connection[1:xxxxxxxxx-dev-shard-00-02.yyyy.mongodb.net:27017:6-155102]: sending heartbeat.\n DateTime=2022-02-17T14:48:01.0370828Z\nMongoDB-SDAM Verbose: 405 : connection[1:xxxxxxxxx-dev-shard-00-00.yyyy.mongodb.net:27017:2-155256]: sent heartbeat in 61040.5318ms.\n DateTime=2022-02-17T14:48:02.0370829Z\nMongoDB-SDAM Verbose: 404 : connection[1:xxxxxxxxx-dev-shard-00-00.yyyy.mongodb.net:27017:2-155256]: sending heartbeat.\n DateTime=2022-02-17T14:48:02.0373158Z\nMongoDB-SDAM Verbose: 405 : connection[1:xxxxxxxxx-dev-shard-00-01.yyyy.mongodb.net:27017:5-161874]: sent heartbeat in 60914.9487ms.\n DateTime=2022-02-17T14:48:02.0385639Z\nMongoDB-SDAM Verbose: 404 : connection[1:xxxxxxxxx-dev-shard-00-01.yyyy.mongodb.net:27017:5-161874]: sending heartbeat.\n DateTime=2022-02-17T14:48:02.0396348Z\ntelnet xxx 27017"}, {"role": "assistant", "content": "Text:Hi, @FrankNielsen,Welcome to the MongoDB Community! Thank you for providing the exception with stack trace. I notice that your cluster topology contains no servers:We have seen this problem in containerized environments due to a DNS issue. I suspect that you are running your app servers in Kubernetes, AKS, or similar environment.The root cause of the problem is a bug in DnsClient.NET. DnsClient.NET is a third-party dependency that we use for SRV and TXT lookups. This bug has been resolved and will be included in the upcoming 2.15.0 release. See CSHARP-4001 for more information on the fix.Prior to the release of the 2.15.0 driver, you can avoid this problem by using the mongodb:// connection string as A, AAAA, and CNAME lookups are not affected by this bug.Sincerely,\nJames\nCode:Servers : []\nmongodb://"}, {"role": "user", "content": "Text:Hi @James_Kovacs ,Thx for the reply, it was worth waiting for.I have looked around your Jira but i am unable to find any roadmap for the v2.15.0 release, can you reveal anything - is it within weeks or months?Cheers, Frank\nCode:"}, {"role": "assistant", "content": "Text:Hi, @FrankNielsen,Glad that I could be of assistance. We are wrapping up some features that we want to include in the 2.15.0 release. Insert usual disclaimer about forward-looking statements, plans could change due to unforeseen circumstances, etc., etc. With that said, the 2.15.0 release is weeks away, not months, though I don\u2019t know for sure exactly when.James\nCode:"}, {"role": "assistant", "content": "Text:Hello,Is there a fix for this issue? I am also facing the same issue. I am using AWS + DocumentDB + SSH Tunnel. When I trying to connect toHowever when I try to connect to AWS DocumentDB from .Net application, I get below exception. I am using the same connection string in Compass and .Net code.A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : \u201c1\u201d, ConnectionMode : \u201cDirect\u201d, Type : \u201cUnknown\u201d, State : \u201cDisconnected\u201d, Servers : [{ ServerId: \u201c{ ClusterId : 1, EndPoint : \u201cUnspecified/documentdb-test.cluster-c7jldipe45vl.ap-south-1.docdb.amazonaws.com:27017\u201d }\u201d, EndPoint: \u201cUnspecified/documentdb-test.cluster-c7jldipe45vl.ap-south-1.docdb.amazonaws.com:27017\u201d, ReasonChanged: \u201cNotSpecified\u201d, State: \u201cDisconnected\u201d, ServerVersion: , TopologyVersion: , Type: \u201cUnknown\u201d, HeartbeatException: \u201cMongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. \u2014> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.31.27.19:27017\nat System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)\nat System.Net.Sockets.Socket.Connect(String host, Int32 port)\nat MongoDB.Driver.Core.Connections.TcpStreamFactory.Connect(Socket socket, EndPoint endPoint, CancellationToken cancellationToken)\nat MongoDB.Driver.Core.Connections.TcpStreamFactory.CreateStream(EndPoint endPoint, CancellationToken cancellationToken)\nat MongoDB.Driver.Core.Connections.SslStreamFactory.CreateStream(EndPoint endPoint, CancellationToken cancellationToken)\nat MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken)\n\u2014 End of inner exception stack trace \u2014\nat MongoDB.Driver.Core.Connections.BinaryConnection.OpenHelper(CancellationToken cancellationToken)\nat MongoDB.Driver.Core.Connections.BinaryConnection.Open(CancellationToken cancellationToken)\nat MongoDB.Driver.Core.Servers.ServerMonitor.InitializeConnection(CancellationToken cancellationToken)\nat MongoDB.Driver.Core.Servers.ServerMonitor.Heartbeat(CancellationToken cancellationToken)\u201d, LastHeartbeatTimestamp: \u201c2022-04-07T05:48:53.4181477Z\u201d, LastUpdateTimestamp: \u201c2022-04-07T05:48:53.4241461Z\u201d }] }.Pleas help.Thanks,\nYogesh\nCode:"}, {"role": "user", "content": "Text:A short follow up, since mognodb driver release v2.15.0 we have not experienced any problems running with the SRV connection string format.Cheers, FrankPS: @Yogesh_Satpute i think your problem is a general first time connection problem!?\nCode:SRV"}, {"role": "assistant", "content": "Text:The exception is there while using 2.17.1 version of the driver, and following the connection string format given by Atlas MongoDB (by checking the Connect->Connect from Application option). I am also trying to get a solution for this exception.\nFollowing is the exception:\nA timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : \u201c1\u201d, Type : \u201cUnknown\u201d, State : \u201cDisconnected\u201d, Servers : }.In this exception it is mentioned that the type is unknown, state is disconnected, server list is empty etc). The servers etc are not mentioned as part of the connection string which I obtained from the AtlasDB->Connect option. I do not know how to proceed and what to do at the moment.\nCode:"}, {"role": "assistant", "content": "Text:Hello, we also use the 2.17.1 version and have the same problem.\nCode:"}, {"role": "assistant", "content": "Text:Some things to check:Given this sounds like a network connectivity/configuration issue rather than a driver bug, I would recommend reaching out to our Atlas Support Team by clicking the in-app chat icon in the lower right corner of MongoDB Atlas.Sincerely,\nJames\nCode:mongoshmongodb+srv://mongodb://"}, {"role": "assistant", "content": "Text:Anytime a \u201ctimeout\u201d error occurs, the first thing to check should be the \u201cnetwork access\u201d control on the server. Most of the time, a timeout is related to an improperly set IP list. to test this possibility, login to your Atlas cluster (or find your private server config files) and head to the security section to allow access from anywhere and test the app that way. also check other security settings so you can at least connect with mongo or mongosh from console, or with Compass.Next is the IP address of the host pc of the application. Having a static domain name does not guarantee having a static IP. your cloud provider might be changing the IP address of the host where your app resides if you don\u2019t have a static IP subscription. they are, after all, virtual PCs or containers and will most possibly be restarted with different IP addresses regularly (disaster recovery, load balancing, etc.). If you have set strict network access in your MongoDB server, then your app will have no chance but give a timeout. In case you host the app on a PC in your own infrastructure, then make sure you give static IP to that PC.if you can eliminate these two possibilities, please add these details to your posts so help can find you faster.\nCode:mongomongoshCompass"}, {"role": "assistant", "content": "Text:The IP is given as 0.0.0.0 inside Atlas Mongo DB network access option.\nI can not set static ip because of work place restrictions. Also there are no proxy settings enforced.\nThe strange thing now is that the access to MongoDB in Atlas is possible since Friday. There has been no changes in the source code, it is the same as when I posted the issue in this forum. It is all strange to me. Does it have anything to do with the fact that I am using shared/free server/cluster option hosted somewhere, and there could be network congestion due to multiple requests from different places to this setup?\nCode:"}, {"role": "assistant", "content": "Text:\u201caccess anywhere\u201d kinda removes all restrictions but there are still many ways to cripple the network access on the app side (before finally blaming a driver). your app seems to work now but may stop again, so best to understand where else the network may diverge expectations. unfortunately, it is like debugging a program and it won\u2019t be apparent immediately what causes the problem.you have said \u201csince Friday\u201d, can you please test your app today/tomorrow again!? it now is pretty possible that your network has a week-long restriction on ports so employees would not surf distracting websites. If your app will again give timeouts today and tomorrow, you need to speak to your administration.\nCode:"}, {"role": "assistant", "content": "Text:Thank you for the reply.\nThere was no intention to blame anything or anyone, thought this was a support forum.\nI already explained there are IT restrictions as per company policy, but do not know up to what extent and where all those restrictions are. Had I known, then I did not have to think much.I close my further communication on this topic here.\nCode:"}, {"role": "assistant", "content": "Text:@Developer_BB Please take a breath first. I am sorry you have offended, but I had/have no intention to offend anyone here.I do not have any way to test your own app and infrastructure on-premise, so I was trying to say what else you can test. we need to first eliminate probable causes, then check for unexpected ones.\nCode:"}, {"role": "assistant", "content": "Text:Have you resolved this issue. I have struggling to find solution for this.\nI am facing the same issue in aws lambda. Please find the details below:Application details: .NET Core application (lambda). .NET mongodb driver (2.18.0), Serverless mongodb instance.Personal Laptop or Local environment\nI have .NET core lamda application and was not working, so I changed DNS to google. It started working in local laptop.Deployed Lambda function\nWhen I deployed the application to aws lambda, it is not working. I have added DataAccess and network access also in Atlas.\nI tried to connect to serverless using mongosh in Cloud 9 machine from the same VPC where lambda is condfigured. I am able to connect to serverless instance.Please help me why I am unable to connect to Serverless mongo instance from lambda.Please let me know if you need more details.\n@James_Kovacs\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MONGOSH updateOne gives error \"could not be cloned\" and tags: ['queries', 'crud', 'mongodb-shell']"}, {"role": "user", "content": "Text:This is a sample of my document structure:Expected outcome after update:I\u2019m trying to replace a substring in the Config property for the whole collection using below code.I\u2019m getting below error when I execute above code in MONGOSH.MondoDB Version: 3.6.8Can anyone help with the issue here?Thanks.\nCode:[\n {\n \"_id\": \"123\",\n \"Config\": \"Some text and then Old substring config for 123\"\n },\n {\n \"_id\": \"456\",\n \"Config\": \"Some more text for another config Old substring config for 456\"\n }\n]\n[\n {\n \"_id\": \"123\",\n \"Config\": \"Some text and then New substring config for 123\"\n },\n {\n \"_id\": \"456\",\n \"Config\": \"Some more text for another config New substring config for 456\"\n }\n]\nConfigdb.MyConfigs.find().forEach(function(doc){ \n var newConfig = doc.Config.replace('Old substring', 'New substring'); \n db.MyConfigs.updateOne(\n {\"_id\", doc._id},\n {$set: { \"Config\": newConfig } }\n ); \n});\nError: clone(t={}){const r=t.loc||{};return e({loc:new Position(\"line\"in r?r.line:this.loc.line,\"column\"in r?r.column:......)} could not be cloned.\n at Object.serialize (node:v8:332:7)\n at u (\\AppData\\Local\\MongoDBCompass\\app-1.34.1\\resources\\app.asar.unpacked\\node_modules\\@mongosh\\node-runtime-worker-thread\\dist\\worker-runtime.js:1917:583764)\n at postMessage (\\AppData\\Local\\MongoDBCompass\\app-1.34.1\\resources\\app.asar.unpacked\\node_modules\\@mongosh\\node-runtime-worker-thread\\dist\\worker-runtime.js:1917:584372)\n at i (\\AppData\\Local\\MongoDBCompass\\app-1.34.1\\resources\\app.asar.unpacked\\node_modules\\@mongosh\\node-runtime-worker-thread\\dist\\worker-runtime.js:1917:5\n3.6.8"}, {"role": "assistant", "content": "Text:Hi @Stak and welcome in the MongoDB Community !I\u2019ll start with a version compatibility issue: https://www.mongodb.com/docs/mongodb-shell/connect/#supported-mongodb-versions.Looks like Mongosh is for MDB 4.0 and above. Can you try with the old \u201cmongo shell\u201d and see if you have the same problem?That being said, for this use case, I would use a bulk write operation to send the updateOne operations in a single bulk instead of firing them one by one. If you really have a lot, I would send them 1000 by 1000 for a first try.Cheers,\nMaxime.\nCode:"}, {"role": "assistant", "content": "Text:I just tested your script and it\u2019s working fine for me on MongoDB 6.0.3 and Mongosh 1.6.0 except that I just had to correct the typo in the filter (\":\" instead of \u201c,\u201d).\nCode:db.MyConfigs.find().forEach(function(doc){\n var newConfig = doc.Config.replace('Old substring', 'New substring'); \n db.MyConfigs.updateOne(\n {\"_id\": doc._id},\n {$set: { \"Config\": newConfig } }\n ); \n});\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: FLE MongoError: BSON field 'insert.jsonSchema' is an unknown field and tags: ['field-encryption']"}, {"role": "user", "content": "Text:Hi Everyone!\nAfter seeing the Field level encryption on a session of Mongo DB live we decided to try implementing it.\nI successfully generated the key vault collection using a AWS KMS key. Next I followed the docs and added a JSON schema to the collection which also worked and I can see the schema in compass. Now what I cant seem to get working is the actual insert. Everything I have tried gives the following error on insert\n\"MongoError: BSON field \u2018insert.jsonSchema\u2019 is an unknown field. \"\nWhat exactly does this error mean with FLE?\nCode:"}, {"role": "user", "content": "Text:I am actually working with dev support now, and they are looking into it.\nCode:"}, {"role": "assistant", "content": "Text:Hi @kyle_mcarthur, and welcome to the forum!Everything I have tried gives the following error on insert\n\"MongoError: BSON field \u2018insert.jsonSchema\u2019 is an unknown field. \"The error message sounds related to a misconfiguration on the application side.\nYou may find the following resources useful:I am actually working with dev support now, and they are looking into it.Feel free to post back here if you have a solution. It may beneficial for other users who may encounter similar configuration issue in the future.Regards,\nWan.\nCode:"}, {"role": "assistant", "content": "Text:Did you find a solution? I am having the same problem.\nCode:"}, {"role": "user", "content": "Text:Hi Emilio,\nYes, my problem was that the mongocryptd process was not running. You will have to download the enterprise edition of mongo and start the process.\nCode:"}, {"role": "assistant", "content": "Text:Thanks Kyle.I am actually using a 4.2 MongoDB Atlas Cluster. However I\u2019m still having that error message.What do you have on your autoEncryption.extraOptions object?I currently have:\nCode:const extraOptions = {\n mongocryptdURI: connectionString,\n mongocryptdBypassSpawn: true,\n };\n"}, {"role": "user", "content": "Text:So that is the part that is confusing, you CANT use your atlas cluster as the encryption process. You have to start the process yourself and use it on the same server your backend is running or expose the process yourself on a separate server and connect with the extra options but you can\u2019t use your atlas instance. I chose the first option and I let the mongo node driver start the process on my server (the driver will try and start it if it\u2019s in your PATH if you remove the bypassSpawn option you have set)\nCode:"}, {"role": "assistant", "content": "Text:Oh ok I understand.I might end up using cloud run base on your solution. Would it be possible for you to share the code regarding including the encryption binary in the docker file? And also the exponential backoff loop you wrote?It would really help me a lot, but if you can\u2019t, that\u2019s fine.I really appreciate all your help man.\nCode:"}, {"role": "user", "content": "Text:So when I talked to dev support about that (i was trying to use my atlas connection string as well at first) they said its because its \u201cclient\u201d encryption but they would take my feedback to the team about using an atlas string. I too am using a serverless architecture but I am using Cloud Run and since that is a docker container I am able to include the encryption binary in the docker container and the node driver starts it automatically.The biggest issue I had on cloud run was the driver code attempts to wait for the process to be started and that didnt always work on cloud run. I basically wrote an exponential backoff loop with a try catch trying to connect to the mongo cluster and now it works flawlessly as it eliminates the race condition with the node driver and the encryption process starting.I use AWS lambda on a different project and with that you would have to do what you said and start the process on a lightsail or ec2 instance. If you havent looked at cloud run I would suggest taking a look as it works great for something like this. If you dont want to use google cloud, aws has fargate that should work similar but its a bit more involved in the setup than cloud run.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Emilio_Lopez and @kyle_mcarthur,So that is the part that is confusing, you CANT use your atlas cluster as the encryption processThe general notion of MongoDB Client-Side Field Level Encryption is that the server never sees the unencrypted values. In this case the driver would automatically encrypt the values via a client-side process (i.e. mongocryptd) before sending data to Atlas.Please note that MongoDB also has Encryption At Rest capability. Atlas encrypts all cluster storage and snapshot volumes, ensuring the security of all cluster data at rest.Would it be possible for you to share the code regarding including the encryption binary in the docker file?If you\u2019re looking for an example Dockerfile that includes just mongocryptd please see\ngithub.com/sindbach/field-level-encryption-docker .I\u2019d also recommend to review FLE: Encryption Components for more information around Client-Side Field Level Encryption.Regards,\nWan.\nCode:mongocryptdDockerfilemongocryptd"}, {"role": "user", "content": "Text:A backoff loop will look something like this:An example docker file is something like:And then in my repo I placed mongocryptd.deb in a folder called encryption.\nCode:let pollForMongo = true;\nlet maxPolls = 0;\nlet backoff = 0;\nwhile (pollForMongo && maxPolls < 10) {\n console.log('polling.....', maxPolls);\n try {\n // eslint-disable-next-line no-await-in-loop\n await mongoose.connect(uri, {\n useUnifiedTopology: true,\n useNewUrlParser: true,\n useCreateIndex: true,\n autoEncryption: {\n keyVaultNamespace,\n kmsProviders,\n schemaMap,\n },\n });\n pollForMongo = false;\n } catch (e) {\n console.log('time until next poll...', 1000 + backoff);\n // eslint-disable-next-line no-await-in-loop\n await sleep(1000 + backoff);\n maxPolls += 1;\n backoff += 1000;\n }\n}\n#Use the official lightweight Node.js 13 image.\n#https://hub.docker.com/_/node\nFROM node:13.5-slim\n\n#Create and change to the app directory.\nWORKDIR ./\n\n#Copy application dependency manifests to the container image.\n#A wildcard is used to ensure both package.json AND package-lock.json are copied.\n#Copying this separately prevents re-running npm install on every code change.\nCOPY package*.json ./\n\n#Install production dependencies.\nRUN npm install --only=production\n\n#Copy local code to the container image.\nCOPY . ./\nRUN apt-get update && apt-get install -y --no-install-recommends apt-utils\nRUN apt install /encryption/mongocryptd.deb\n\n#Run the web service on container startup.\nCMD [ \"npm\", \"start\" ]\n"}, {"role": "assistant", "content": "Text:Thanks man!By the way, are you having any performance issues with mongocryptd? My writes are taking twice the amount of time even if the document I am saving doesn\u2019t have any encrypted fields. Also when I make 20+ writes concurrently it just stops working.\nCode:"}, {"role": "user", "content": "Text:I have fortunately not had any performance problems with the encryption process. Let me know if you find out the cause.\nCode:"}, {"role": "assistant", "content": "Text:Nevermind I figured it out\nCode:"}, {"role": "assistant", "content": "Text:I will.Did you have this error when running it on docker?Error: /app/node_modules/mongodb-client-encryption/build/Release/mongocrypt.node: invalid ELF header.\nCode:"}, {"role": "assistant", "content": "Text:hi are you downloaded \u2018mongocryptd.deb\u2019 with these config? Screenshot 2020-09-13 at 12.39.49 PM626\u00d7616 35.6 KBI am not able to install mongocryptd.deb due to dependences.\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python-pymongo\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongodb-java\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018jmeter-mongodb\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python3-pymongo\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libcatmandu-store-mongodb-perl\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongodb-perl\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongo-client-dev\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongo-client0\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongo-client-doc\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongo-client0-dbg\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongoc-1.0-0\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongoc-dev\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongoc-doc\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongoclient-dev\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libmongoclient0\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018php-mongodb\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018php-doctrine-mongodb-odm\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018php-horde-mongo\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018php7.0-mongodb\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018php-mongo\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018libpocomongodb46\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018prometheus-mongodb-exporter\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018puppet-module-puppetlabs-mongodb\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python-pymongo-ext\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python-pymongo-doc\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python2.7-pymongo\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python2.7-pymongo-ext\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python3-pymongo-ext\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python-mongoengine\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python2.7-mongoengine\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python-mongoengine-doc\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018python3-mongoengine\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018rsyslog-mongodb\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018ruby-em-mongo\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018ruby-mongo\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018syslog-ng-mod-mongodb\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018uwsgi-mongodb-plugins\u2019 was not found\nE: Release \u2018mongocryptd.deb\u2019 for \u2018w1retap-mongo\u2019 was not found\nCode:"}, {"role": "assistant", "content": "Text:Hi @Ben_Luk, and welcome to the forum!You can install mongocryptd from apt-get on Ubuntu. For example in a Dockerfile:See also github.com/sindbach/field-level-encryption-docker/node for a working example.Regards,\nWan\nCode:mongocryptdapt-getDockerfileRUN wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | apt-key add -\nRUN echo \"deb [ arch=amd64,arm64,s390x ] http://repo.mongodb.com/apt/ubuntu focal/mongodb-enterprise/4.4 multiverse\" | tee /etc/apt/sources.list.d/mongodb-enterprise.list\nRUN apt-get update && apt-get install -y mongodb-enterprise-cryptd=4.4.1\n"}, {"role": "assistant", "content": "Text:Hello Team,I am facing the same issue, can some one have solution for this?\nCode:"}, {"role": "assistant", "content": "Text:@wan whats the point of having \u201cmongocryptdURI\u201d extra option then?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: \ud83c\udf31 Hey, friends! I'm Lauren and tags: []"}, {"role": "user", "content": "Text:Hey, friends!I\u2019m Lauren Schaefer, a developer advocate at MongoDB. I\u2019ve been with MongoDB for a little over a year, and I love helping users get started with the technology. I\u2019m on the Content team, so I spend most of my team creating blogs and videos.I work out of my home office in Pennsylvania, which is on the east coast of the United States. I love traveling and speaking at conferences. Maybe we\u2019ll bump into each other at a developer conference in the future. I\u2019m a big advocate of remote work. It has enabled me to create a career I thoroughly enjoy despite living in the rural locations where my husband is employed. I gave a talk entitled Does Remote Work Really Work? at Pycon last year. Check it out.In my free time, I enjoy hanging out with my daughter and husband, watching comedies (I\u2019m currently enjoying season 3 of The Marvelous Mrs. Maisel), and empowering and encouraging other women.You can find me on Twitter and LinkedIn. See you around the community!\nCode:"}, {"role": "assistant", "content": "Text:Hi I have a few questions for a school project the first question is.\nWhat made you get into programming ?\n@Lauren_Schaefer\nCode:"}, {"role": "user", "content": "Text:Welcome to the community! I\u2019m glad you made your way here from TikTok! So what made me get into programming?My family got the internet when I was in middle school, and I was fascinated. I remember creating a personal webpage using a basic GUI tool and thinking how fun it was. At some point, I got interested in the code behind the webpages. I went to a bookstore (yes, a real bookstore!) and picked up HTML for Dummies. I read the whole thing and had fun building out my own personal website.When I was trying to figure out what service project to do for my Girl Scout Gold Award (equivalent to an Eagle Scout), I knew I wanted to do something with the web. My troop leader said she knew a local nonprofit that needed a website. I decided to teach myself to use Dreamweaver and Flash (Flash was super hot tech back then) to build the website for them. I had a lot of fun creating the site and then training a staff member how to update the site, so it could continue on after I left for college.When I needed to pick a college major, I really didn\u2019t know what to pick. Math had always been my favorite subject in school, but I didn\u2019t know what a professional mathematician really did. I had always liked computers, so I decided to roll with that. Computer Science would be my major.No one told me that Computer Science was \u201cfor guys.\u201d I truly had no idea. My parents had no idea.I also had no idea that many of my classmates would already have programming experience. They had taken programming courses in high school (my high school didn\u2019t offer any), or they had taught themselves to program. I remember in my first programming course the instructor asked us how many of us had programming experience. I raised my hand. A classmate asked me what I had programmed. I told him I had built websites using HTML. He informed that wasn\u2019t real programming.When I took my second-level programming course, I discovered that programming was a male-dominated field. I was the only woman in my class. And I was shocked. Why had no one told me?I knew so little in comparison to many of my classmates, and I was constantly aware of the fact that I was the only female student.I considered switching majors many times. But I honestly couldn\u2019t think of another major I would enjoy doing. Programming was a struggle for me initially (I remember being very confused at variable assignment \u2013 why were we saying two things were equal when they clearly were not?). I spent a LOT of time in office hours and a LOT of time with my classmates who helped me understand the material.I remember when the instructor in my second-level programming course passed out our graded exams, my classmates were shocked that I got an A. I had to work so hard in those programming courses as I felt like I was catching up with my classmates.Anyway, I never did find a major that sounded more interesting than Computer Science, so I graduated with a BS in Computer Science. I decided to stick around and get a MS in Computer Science. And then I was hired as a software engineer.Well, that was probably more info than you were looking for, but there it is. Let me know if you have any other questions. \nCode:"}, {"role": "assistant", "content": "Text:Wow, I felt a similar way when deciding what I would major in because computer science is the only thing I\u2019m interested in because of my curiosity of how things work. You actually answered a lot of my questions that already had so thank you ! I only have two more \u2026As you most likely know homelessness is a huge issue. If I wanted to develop an app where people can individually donate to homeless people how would developers go about starting a project like this?Lastly, why do you think programming has one of the best job outlooks in the future ?\n@Lauren_Schaefer\nCode:"}, {"role": "assistant", "content": "Text:Also what programming language do you mostly use now ?\nAnd what language is best to learn when looking for a job ?\n@Lauren_Schaefer\nCode:"}, {"role": "user", "content": "Text:Regarding the app - It\u2019s unclear to me what stage of app development you\u2019re in.If you\u2019re at the very beginning, you probably need to start with some requirements gathering. What will actually help? What will be effective? Will donations be tax deductible? Why would people donate through your app rather than existing channels? Can you partner with existing organizations? etcThinking lean, you may want to start by validating your idea while building as little as possible. Can you accept donations through an existing system (mail, Paypal, gofundme, etc) to validate people are willing to give and that you have a way to effectively distribute donations.Once you\u2019ve validated your idea, you\u2019re ready to build. This is the fun part. If you\u2019re looking for a platform to build your app, I recommend MongoDB Realm. It has a lot of features that make building web and mobile apps easier. Things like serverless functions, GraphQL, and a mobile database.Why do I think programming has one of the best job outlooks in the future?Every company is becoming a software company. Nearly every business needs software in order to stay competitive or move ahead. Programmers make this happen.Also what programming language do you mostly use now ?JavaScriptAnd what language is best to learn when looking for a job ?Some employers look for experience in specific programming languages while others acknowledge that, if you know one programming language, you can probably pick up another language fairly easily. I learned Java in school, but I haven\u2019t touched it in years. Throughout my career, I\u2019ve picked up JavaScript, Python, and PHP.I recommend checking out the Stack Overflow Developer Survey for more information on programming language trends.\nCode:"}, {"role": "assistant", "content": "Text:This really helped a lot thank you and thank you for your time ! \nCode:"}, {"role": "user", "content": "Text:You\u2019re welcome, @Tyree_mccloud!\nCode:"}, {"role": "assistant", "content": "Text:2 posts were split to a new topic: Adjusting results of $lookup aggregation from an Array\nCode:"}, {"role": "assistant", "content": "Text:Hi @Lauren_Schaefer ! I am really enjoying your teaching style so I wanted to introduce myself and say thanks. The course on Schema Anti-patterns I followed with you was very well taught\u2026and super funny. My favorite part is \u201cAndy has acquired 32,563 lions and a country can have many policies, Finland has decide to use Lions in lue of military for it\u2019s national defense policies\u201d . I did learn so much as well. From why an array is NOT a good option for storing huge unbounded lists to reasons why you should drop a collection(the collection size is mostly indexes or if it\u2019s just empty). I learned methods of restructuring data to fit use cases or the option to move to a larger cluster if necessary and the two collation strengths that provide case-insensitivity(1 and 2 obvi ). You taught us that the rule of thumb when modeling our data should be, Data that is accessed together should be stored together and that the best practices suggest considering your particular use case when determining how to model our data. SO, in conclusion, I would have to say you deserve to own Leslie Nope\u2019s quote \u201cI\u2019m big enough to admit, that I often inspire myself!\u201d That\u2019s classic humor sandwich teaching, which I appreciate! \nCode:"}, {"role": "user", "content": "Text:@Jason_Nutt Thank you sooooo much! Finding that other people not only enjoy your content but have retained the main points is the highest compliment. You have just made my day. \n\nCode:"}, {"role": "assistant", "content": "Text:I just maxed out my hearts on that reply lol. So you made mine too! I\u2019m going to try and make a D&D world database based on the ideas I\u2019m getting from the Pawnee model Untied Nations presentation. Watching it again on a different platform this morning and writing all my ideas down on stickys. I love your teaching style. Any suggestions or direction for growth are welcome. You have inspired and encouraged and most importantly \u2026we laughed lol. \u201cok so I din\u2019t do model United Nations in High school\u2026OH WAIT, WE TOTALLY DID!\u201d ~Best quote of the lesson?\nCode:"}, {"role": "user", "content": "Text:In addition to Parks and Rec, I\u2019m also a huge fan of Community. They did two D&D episode (I assume we\u2019re talking about Dungeons and Dragons?)The MongoDB University Courses are awesome. I definitely recommend those.I also include a list of data modeling resources at the bottom of this blog post: A Summary of Schema Design Anti-Patterns and How to Spot Them | MongoDBIf you\u2019re interested in Node, I have a Node Quick Start video and blog series: Connect to a MongoDB Database Using Node.js | MongoDB Blog\nCode:"}, {"role": "assistant", "content": "Text:They did two D&D episode (I assume we\u2019re talking about Dungeons and Dragons?)That is the only D & D I know of! Yay Community! My wife and I love that one too. Thanks for the direction. @Lauren_Schaefer . I\u2019m well into the path into MongoDB University also ( I think I have done something like 7 course and data modeling & anti-pattern schema design is my favorite thing so far ), that\u2019s what has led me to you and Anti-patterns. Super excited about the growth I am seeing with y\u2019all!\nCode:"}, {"role": "assistant", "content": "Text:4 posts were split to a new topic: Haven\u2019t received my Anti-Patterns badge yet\nCode:"}, {"role": "assistant", "content": "Text:A post was split to a new topic: Images aren\u2019t displaying on the Champions page\nCode:"}, {"role": "assistant", "content": "Text:I need some help from you let me know when you available to I can post my question\nCode:"}, {"role": "assistant", "content": "Text:Hello @Sheroz_Khan\nwelcome to the community \nWe are here to get your MongoDB questions answered. You, and the community, will most benefit from your question and the answer when you phrase your question and post it in a fitting category. I highly recommend to read the Getting started section. You will find there a lot of valuable information. Also the chance to get a fast response is much higher when you ask the community, individual persons might be busy.\nRegards,\nMichael\nCode:"}, {"role": "assistant", "content": "Text:A post was split to a new topic: Can I use MongoDB as my primary db for text search engine, that contain approx billion records\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Convert standalone docker-compose version to replica set primary and tags: ['replication', 'mongodb-shell', 'containers']"}, {"role": "user", "content": "Text:I have the following docker-compose file that starts my MongoDB as standalone (in PROD).My goal: convert this instance to the PRIMARY in a replica set.\nI have another instance running, freshly set up, currently doing nothing (if this works, I\u2019ll add a 3rd).My thinking was that, stopping the instance, uncommenting the \u2018entrypoint\u2019 line and bringing the instance back up, would convert the standalone instance into a replica set instance, as described in this tutorial .\nHowever, when doing this, I get:Any hints in what I\u2019m doing wrong?\nCode:version: '3.1'\n\nservices:\n\n mongo:\n image: mongo\n restart: always\n # entrypoint: [ \"/usr/bin/mongod\", \"--bind_ip_all\", \"--replSet\", \"rs0\" ]\n ports:\n - 27017:27017 # admin\n environment:\n MONGO_INITDB_ROOT_USERNAME: admin\n MONGO_INITDB_ROOT_PASSWORD: superlongpassword\n volumes:\n - /host/mongodb:/data/db\n(in mongosh):\ntest> rs.initiate()\nMongoServerError: already initialized (PS: I had tried this before...)\ntest> rs.status()\nMongoServerError: Our replica set config is invalid or we are not a member of it.\n\n"}, {"role": "assistant", "content": "Text:What message you got when you ran rs.initiate() first time?\nOnce you start your mongod with replset and run rs.initiate() it should become primary\nCheck this link.I don\u2019t know about dockerI've a Docker instance with mongo. This run as standalone configuration. Now I w\u2026ould to change `entrypoint.sh` to run itself as replica set following [official guide standalone to replica set](http://docs.mongodb.org/manual/tutorial/convert-standalone-to-replica-set/)\n\nAny suggestion? I've tried to manually setting up entrypoint.sh but it have crashed my container.\nCode:"}, {"role": "user", "content": "Text:I wish I knew Is there a config file somewhere that stores info about whether a node is in a replica set or not? Can you revert a node in a replica set to again be a standalone version (such that, when started again enabling replica set and rs.initiate(), it will actually say it\u2019s in a replica set)?\nCode:environment:\n MONGO_INITDB_ROOT_USERNAME:\n"}, {"role": "assistant", "content": "Text:Mongod.conf is the configuration file where we define replica parameters but in your case whatever commands mentioned at entry point are run when you initialise your docker\nSo comment this entry and restart to get back to standalone but advice you not to do experiments on prod\nAs mentioned before I don\u2019t know about docker setup but many docs available\nCheck this linkThis tutorial will show how to create a replica set in MongoDB, then use Docker compose to make a more straightforward setup.\nCode:"}, {"role": "assistant", "content": "Text:The error you are receiving is consistent with the scenario that the replSet was previously initialized and then the --replSet name changed.Once you are back to standalone you need to drop the local database to remove the previous replicaSet configuration which will allow you to try again.I set the parameters using command command in docker-compose:\nCode:local//run in mongosh\nuse local\ndb.dropDatabase()\ncommandversion: \"3.8\"\nservices:\n mongo-0-a:\n image: mongo:6.0\n command: --wiredTigerCacheSizeGB 0.25 --replSet s0 \n volumes:\n - mongo-0-a:/data/db\nvolumes:\n mongo-0-a:\n"}, {"role": "assistant", "content": "Text:\"--replSet\", \"rs0\"if you start your instances with this parameter set, no matter how many instances you have, you use rs.initiate() only once on one of them and then use rs.add() to add other members.you could also use a configuration on initialization if you knew what would their IP addresses be. it is a tedious thing to set up but not impossible (play on compose file):\nCode:\"--replSet\", \"rs0\"rs.initiate()rs.add()rs.initiate({\n _id: \"rs0\", members: [\n { _id : 0, host : \"mongo1:27017\"},\n { _id : 1, host : \"mongo2:27017\"},\n { _id : 2, host : \"mongo3:27017\"}\n] } )\n"}, {"role": "user", "content": "Text:Dropping the local db and restarting with the replica set option worked for me.Next issue: I\u2019m running version 6.0.3 and tried to add a Raspberry Pi in the mix. However, the last version that works is 4.4. rs.status() complains that:remote host has incompatible wire version: Server min and max wire version (9,9) is incompatible with client min wire version (17,17).You (client) are attempting to connect to a node (server) with a binary version with which you (client) no longer accept connections. Please upgrade the server\u2019s binary version.Can I downgrade my 6.0.3 version to be 4.4, or is that not advisable? If not, how would you suggest I add a replica set member with 4.4?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Delhi-NCR MUG: Building React Applications with Data APIs & Scalability With MongoDB Atlas! and tags: ['atlas', 'react-js', 'data-api', 'delhi-mug']"}, {"role": "user", "content": "Text:\nDelhi - MUG1920\u00d71080 255 KB\nPlease note: The RSVP above is a waitlist, we will be confirming your attendance a few days before the event.Delhi-NCR MongoDB User Group is organizing a meetup in the last week of November on Saturday, November 26, 2022, at 11:00 AM at LinkedIn Office, Gurugram.The day will include two sessions, In the beginning, Manan Varma, (Head of Engineering @PhysicsWallah) will talk about - How to Scale with MongoDB Atlas.His sessions will be followed by Shreya Prasad, (Software Engineer @Intuit) who will talk about how you to build apps with React and MongoDB Data APIs.We will also have some fun activities like Trivia and Spot the Bug along with an amazing Lunch .This is a meet-up for you where we\u2019re trying to attract newcomers, experienced developers, architects, and startup founders to come, share ideas and case studies as well as meet new people in the community. Come join us for a day of learning lunch and fun\u2026!Please Note: We have limited seats available for the event. RSVP on the event page to express your interest and enter the waitlist. We will reach out to you with a confirmation email to confirm your attendance.Event Type: In-Person\n Location: LinkedIn Office, Gurugram .\n Tower 8th Road, Sikandarpur Upas, DLF Cyber City, DLF Phase 2, Sector 24, Gurugram, Haryana 122022To join the waitlist - Please click on the \u201c RSVP \u201d link at the top of this event page if you plan to attend. The link should change to a green button if you RSVPed. Please Note: We have limited seats available for the event. RSVP on the event page to express your interest and enter the waitlist. We will reach out to you with a confirmation email to confirm your attendance.\nmanan verma800\u00d7800 70.9 KB\nHead of Eng, PhysicsWallah (PW)\u2013\nshreya prasad596\u00d7596 60.2 KB\nSoftware Engineer @ Intuit\nshrey batra800\u00d7800 214 KB\nLead - MUG Delhi NCR | Sr. SWE @ LinkedInLead - MUG Delhi NCRJoin the Delhi-NCR group to stay updated with upcoming meetups and discussions.\nCode:Head of Eng, PhysicsWallah (PW)Software Engineer @ IntuitLead - MUG Delhi NCR | Sr. SWE @ LinkedInLead - MUG Delhi NCR"}, {"role": "assistant", "content": "Text:Hi, Not able to RSVP. Getting error 500\nCode:"}, {"role": "assistant", "content": "Text:exactly , its showing error\nCode:"}, {"role": "assistant", "content": "Text:getting 500 error on RSVP \u2026please add me for event -email-vishwakshivam@gmail.com\nCode:"}, {"role": "assistant", "content": "Text:Getting 500 error when clicking on RSVP\nCode:"}, {"role": "assistant", "content": "Text:Hello @Manan_Bedi, @Arman_Mansury, @Shivam_Vishwakarma, @Shivam_Gupta6!\nThanks for letting us know!We are actively working to resolve the issue. Will let you know here once it\u2019s resolved and you can RSVP to get added to the waitlist \nCode:"}, {"role": "assistant", "content": "Text:Unable to register, getting a 500 error\nCode:"}, {"role": "assistant", "content": "Text:Hi everyone, please tag me when the registration issue is resolved. Looking forward to the the exciting event!\nCode:"}, {"role": "assistant", "content": "Text:Hi, I\u2019m getting the same error. \nCode:"}, {"role": "assistant", "content": "Text:Hi, please let us know by tagging when RSVP issue resolves, thanks.\nCode:"}, {"role": "assistant", "content": "Text:Unable to get rspv showing 500 error\nCode:"}, {"role": "assistant", "content": "Text:Please fix this\nThank you\nCode:"}, {"role": "user", "content": "Text:Hi @Sidharth_Dang , @Avneet_Singh_20CS133 , @Sohil_Khanduja , @Pragya_Bansal , @Nimish_Jain , @Tushar_Anand1 , @Shivam_Gupta6 , @Shivam_Vishwakarma , @Arman_Mansury , @Manan_BediThe RSVPs are now fixed, please go ahead and RSVP.\nKeep in mind, this is for waitlist and we will be sending separate confirmation mails to people on waitlist\u2026!Thanks \nCode:"}, {"role": "assistant", "content": "Text:RSVP is working now. Thanks a lot!\nLooking forward to attend\ud83d\ude4c\nCode:"}, {"role": "assistant", "content": "Text:RSVP is not working properly.\nCode:"}, {"role": "assistant", "content": "Text:Hey, @Mayank_Agarwal I just tested and it\u2019s working fine. Can you check again - click on the \u201cRSVP\u201d button and it will turn Green if you RSVPed There\u2019s a known error though if you try seeing the RSVP list by clicking on the number.\nCode:"}, {"role": "assistant", "content": "Text:Yes, it is working fine now.\nCode:"}, {"role": "assistant", "content": "Text:@Harshit 403 error. RSVP booked out?\nCode:"}, {"role": "assistant", "content": "Text:+1 to this, couldn\u2019t rsvp earlier as well due to issue saying you can\u2019t login with this ip address \nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Combine $text with $regex and tags: ['queries', 'atlas-search', 'text-search']"}, {"role": "user", "content": "Text:Hi everyone,I would like to obtain the results of a text search with the results of a regex. In particular, assuming that the input string is \u201csubstring\u201d, I would like to be able to do the following filter:{ $or : [ { name : { $regex : \u201c.substring.\u201d } }, {$text : { $search: \u201csubstring\u201d } } ] }Of course, I\u2019ve previously created the $text index on \u201cname\u201d field, however it gives me a Mongo Error since $or and $text operator cannot be used together.\nHow can I achieve this filtering?Thanks in advance\nCode:"}, {"role": "assistant", "content": "Text:Hi @Matteo_Tarantino ,Why do you need this kind of double search if you already perform a text search. In general we recommend using Atlas search for full text searches if it happens that your cluster is an Atlas cluster:Learn how to use a regular expression in your Atlas Search query.If you still insist on running this query using the traditional text indexes , I believe the use of $unionWith aggregation might work:Ty\nCode:[{$match: {\n $text: {\n $search: 'substring'\n }\n}}, {$unionWith: {\n coll: '',\n pipeline: [\n {\n $match: {\n name: {\n $regex: '. substring.'\n }\n }\n }\n ]\n}}]\n"}, {"role": "user", "content": "Text:Hi @Pavel_Duchovny ,to the best of my knowledge $search operator does not find a match if the searching string is actually a substring of the field I\u2019m seaching on. In particular:Suppose that you are searching by name and the name field of a document is \u201cMatteo\u201d. If the searching string is \u201catte\u201d the $search operator discards that document. At leats I\u2019m experiencing this behavior when applying the $search operator in a serverless atlas cluster. Is it correct?\nCode:$searchnamename$search$search"}, {"role": "assistant", "content": "Text:Hi @Matteo_Tarantino ,Do you mean when using the \u201cregex\u201d operator in the $search stage of Atlas Search?With regex operator (I linked you with\u2026) you can search for partial expressions of a word:In this example I search the sample_mflix.movies collection using a regex .*los.* and it find strings like:Thanks\nPavel\nCode:[{$search: {\n regex: {\n path: 'title',\n query: '.*los.*',\n allowAnalyzedField: true\n }\n}}]\nsample_mflix.movies.*los.*title : \"Broken Blossoms or The Yellow Man and the Girl\"\n...\ntitle : \"The Lost World\"\n"}, {"role": "assistant", "content": "Text:This operator concatenates two regular expressions a and b . No character represents this word combiner operator; you simply put b after a . The result is a regular expression that will match a string if a matches its first part and b matches the rest.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Richard_Gravener ,I need an example document and query\u2026\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Change stream projection, getting last resume token and tags: ['change-streams']"}, {"role": "user", "content": "Text:The project that I work on currently works by tailing the oplog. When the project starts, it queries the oplog and obtains the last entry in the oplog before we began a series of tasks and state changes. We record this oplog position at bootstrap as we want to make sure that when we transition to a later phase that we begin processing oplog entries without lose of events.I\u2019m currently looking into whether we can transition this to using change streams instead. What the code is not yet designed to support is creating a change stream earlier on in the process and reusing that stream in the later phase so what I would like to do is something similar to the oplog approach where I determine a check-point in the stream and restart the stream later using that check-point.So is there a way to query a change stream and ask for the last/most recent resumeToken? I\u2019d like to stash this resume token in our cache and then use this in the later phase to restart the change stream specifying that resume token as the startAfter argument.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Chris_Cranford, welcome!So is there a way to query a change stream and ask for the last/most recent resumeToken ?Generally, as you watch a collection you cache the resume token. If there\u2019s any interruptions to the watch process, you can restore the token from the cache. For example using MongoDB Java driver:You can then resume from a token as below:You could perhaps store the resumeToken caches with some metadata information that you could query later on.See also Resume a Change Stream.Regards,\nWan.\nCode:MongoCursor> cursor = collection.watch().iterator();\nChangeStreamDocument next = cursor.next();\nBsonDocument resumeToken = next.getResumeToken();\ncursor = collection.watch().resumeAfter(resumeToken).iterator();\n"}, {"role": "user", "content": "Text:Hi @wanPerhaps a bit more background here might help illustrate my issue.The Debezium project operates in 2 phases, a snapshot and a streaming phase. In a situation where the user is creating a new connector and performing the snapshot and streaming operations, we first want to record some marker to indicate that anything prior will be included in the snapshot phase and that any changes done after that marker will be picked up by the streaming phase.In the traditional oplog scenario, we could capture the last timestamp from the oplog before we begin the snapshot so we know where we need to start tailing the oplog from when streaming begins.Now to be clear, I\u2019m not talking about restarts of Debezium here as we already cache the resumeToken from the change stream so that its available during restarts, which fits to what you described.The niche problem is more to do with the notion of a user creating a new connector and how that would work during the small window between snapshot and streaming phases. What I need here is to get this marker before I begin the snapshot so that I can control the point where the change stream should effectively start when streaming begins. In other words, I need to guarantee that whatever happens to the database while snapshotting is running is later captured during streaming.It doesn\u2019t sound like with how the API is written there is such a way to obtain this marker as we have traditionally done so by basically getting the last event in the oplog before we begin snapshotting.If that is all true and correct, I think there is maybe only a single option and that is we would need to open the change stream where we would normally get the last event from the oplog and somehow provide this stream to the streaming phase rather than opening it up later like we\u2019re doing.It seems unfortunate there is no way to open a change stream and issue some type of projection or query to have it return the last event in the stream.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Chris_Cranford,Thanks for providing more context.In the traditional oplog scenario, we could capture the last timestamp from the oplog before we begin the snapshot so we know where we need to start tailing the oplog from when streaming begins.If that\u2019s your use case, you could utilise startAtOperationTime instead.Available in MongoDB 4.0+, you can specify a startAtOperationTime to open the cursor at a particular point in time (timestamp). Just make sure the time range is within the oplog range. Using MongoDB Java driver (v3.12) as an example. :See also Change Event\u2019 s clusterTime field.Regards,\nWan.\nCode:startAtOperationTimestartAtOperationTimeoplogChangeStreamIterable cs = collection.watch();\n// Unix timestamp in seconds, with increment 1\ncs = cs.startAtOperationTime(new BsonTimestamp(1587009106, 1));\nMongoCursor cursor = cs.iterator();\nclusterTime"}, {"role": "user", "content": "Text:Awesome, I think I understand. I\u2019ll give this a shot next week and report back with how that works.\nCode:"}, {"role": "assistant", "content": "Text:Hi @wan\nI\u2019m faced with this issue. But I\u2019m using AWS DocumentDB and it only compatibility with MongoDB 3.6.\nCode:"}, {"role": "assistant", "content": "Text:Hi @chu_quang, and welcome to the forum!But I\u2019m using AWS DocumentDB and it only compatibility with MongoDB 3.6.AWS DocumentDB API is an emulation of MongoDB which differs in features, compatibility, and implementation from an actual MongoDB deployment. AWS DocumentDB suggestion of API version support (eg 3.6) is referring to the wire protocol used rather than the full MongoDB feature set for that version.For further questions on AWS DocumentDB I\u2019d suggest to contact AWS.If you want to use the latest MongoDB features and drivers without emulation I\u2019d strongly recommend to use MongoDB Atlas.Regards,\nWan.\nCode:"}, {"role": "assistant", "content": "Text:Thank for your support. I will contact AWS.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Chris_Cranford were you able to resolve this issue/approach?Taking a guess, is this for the Debezium mongodb connector for allowing to load an entire collection upon creation + then start with the CDC via change streams\u2026?Is this \u201csnapshot.mode\u201d: \u201cinitial\u201d of Debezium connector for MongoDB :: Debezium Documentation?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoError: Cannot use a session that has ended and tags: ['node-js']"}, {"role": "user", "content": "Text:My Code: hatebinMy Error: \u201c(node:28581) UnhandledPromiseRejectionWarning: MongoError: Cannot use a session that has ended\u201dThis is for my discord bot, but on my pc everything works fine but on my server I get this error.\nAnd I have the exact same mongoose versionHelp pls\nCode:"}, {"role": "assistant", "content": "Text:Hi @tomson welcome to the community.If I have to guess, it\u2019s due to the mongoose.connection.close(); statement in the function you posted.Mongoose and the MongoDB node driver encourages the use of a global variable to connect once to the database during the lifetime of the application, and discourage the practice of connect-disconnect for every operation. This is because the MongoDB driver keeps a connection pool and will create/reuse connections as needed. Note that this is the reason why the connection object is a global object in Mongoose.Could you try removing the mongoose.connection.close(); statement and see if the issue persists?I would also replace the finally block there with catch to grab any errors in the try block.Best regards,\nKevin\nCode:mongoose.connection.close();mongoose.connection.close();finallycatchtry"}, {"role": "assistant", "content": "Text:Thank you for the help brother \nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Installing mongodb over Ubuntu 22.04 and tags: ['sharding']"}, {"role": "user", "content": "Text:Hello,These days Ubuntu published their new long term supported version, 22.04, and it is not possible to install mongodb because they don\u2019t support libssl1.1 anymore:I googled it, but I did not find anywhere nobody who could solve this problem. Any ideas?\nThank you!\nCode:The following packages have unmet dependencies:\n mongodb-org-mongos : Depends: libssl1.1 (>= 1.1.1) but it is not installable\n mongodb-org-server : Depends: libssl1.1 (>= 1.1.1) but it is not installable\n mongodb-org-shell : Depends: libssl1.1 (>= 1.1.1) but it is not installable\n"}, {"role": "assistant", "content": "Text:Are you following these directions?\nCode:"}, {"role": "user", "content": "Text:Yes, but it\u2019s a dependency problem. I tried mongo 4.4 and 5.0, to no avail: same error on both.\nCode:"}, {"role": "assistant", "content": "Text:Aha. I\u2019m on 20.0x and haven\u2019t upgraded to 22 yet. I\u2019m sure @Stennie_X will have the answer!\nCode:"}, {"role": "assistant", "content": "Text:This worked for me\nCode:echo \"deb http://security.ubuntu.com/ubuntu impish-security main\" | sudo tee /etc/apt/sources.list.d/impish-security.list\nsudo apt-get update\nsudo apt-get install libssl1.1\n"}, {"role": "assistant", "content": "Text:Just apt installing openssl 1.1 sounds like a recipe for disaster.\nUbuntu 22.04 already has openssl 3 installed.\nI think a MongoDB team member had best respond to this issue with a recommended path\n\u2026 @Stennie_X ?\nCode:"}, {"role": "assistant", "content": "Text:Hi folks,Ubuntu 22.04 was released less than a week ago so doesn\u2019t have official MongoDB packages available yet. The build team is aware and will set up appropriate packaging & testing infrastructure to validate new packages.Relevant Jira issues to watch are:I don\u2019t have a specific ETA to share at the moment, but I\u2019d generally recommend waiting for essential software packages to be available before committing to major O/S upgrades.If you are an early adopter of a new O/S release, suggested interim workarounds would be:Run your MongoDB deployment on separate hosts with supported O/S versions (eg 20.04 LTS)Run MongoDB in a container/VM with a supported O/S versionUse a hosted version of MongoDB (eg MongoDB Atlas) so you have fewer direct dependencies on O/S updatesAll of these approaches use official binaries, so you are less likely to run into novel issues.For a development environment you could also consider:Building MongoDB from sourceTrying to install or build missing dependenciesHowever, I would be very wary of mixing & matching packages intended for different O/S versions (especially for a production environment) as those combinations have not been thoroughly tested.Regards,\nStennie\nCode:"}, {"role": "user", "content": "Text:Ok, thank you! Will wait for the support then. Out of ignorance, may I ask if generating a snap instead of a deb could solve the dependency problem and other possible library conflicts?\nCode:"}, {"role": "assistant", "content": "Text:Thanks, It worked for me as well!!\nCode:"}, {"role": "assistant", "content": "Text:Hi there, hope you\u2019re doing well. I\u2019m currently using MongoDB in Docker and it is good enough while waiting for new update from the MongoDB team.to start MongoDB (automatically restart):\nsudo docker run -dp 27017:27017 -v local-mongo:/data/db --name local-mongo --restart=always mongoTo access into running local-mongo container:\nsudo docker exec -it local-mongo shThen type mongo and you\u2019re good to go!\nCode:sudo docker run -dp 27017:27017 -v local-mongo:/data/db --name local-mongo --restart=always mongolocal-mongosudo docker exec -it local-mongo shmongo"}, {"role": "assistant", "content": "Text:This worked for me as well. Still waiting for offcial release.\nCode:"}, {"role": "assistant", "content": "Text:Can you drop the process of installing mongodb on docker ??\nCode:"}, {"role": "assistant", "content": "Text:Hi Alexander, I\u2019ve already posted the process above. I\u2019ll re-post it in case you didn\u2019t see it:\nsudo docker run -dp 27017:27017 -v local-mongo:/data/db --name local-mongo --restart=always mongo\nCode:sudo docker run -dp 27017:27017 -v local-mongo:/data/db --name local-mongo --restart=always mongo"}, {"role": "assistant", "content": "Text:Thank you. Will try it now\nCode:"}, {"role": "assistant", "content": "Text:As a sidenote, you can still download some of the mongodb binaries from the official ubuntu repo (not recommended by mongodb though), if you just playing around it is fine imho. Example:You can see it skips libssl1.1\nCode:sudo apt-get install mongo\nmongocli mongodb-mongosh ...\nsudo apt-get install mongodb-mongosh \nReading package lists... Done\nBuilding dependency tree... Done\nReading state information... Done\nRecommended packages:\n libssl1.1\n"}, {"role": "assistant", "content": "Text:Is there any ETA on 22.04 packages? Or even RHEL 9?Any rough estimate? It\u2019s the only blocker we have now for both distros.\nCode:"}, {"role": "assistant", "content": "Text:Hey fellas.\nIs there already any \u201cofficial\u201d solution to that problem?\nI also struggle with Ubuntu 22.04 LTS, cannot install MongoDB on it.\nCode:"}, {"role": "assistant", "content": "Text:Hi folks! Ubuntu 22.04 has been out for almost 3 months now, when will we be able to install the official version of mongo without all sorts of hacks and tweaks?\nCode:"}, {"role": "assistant", "content": "Text:I got mongodb 5.0.9 installed on ubuntu 22.05\u2026 but boy\u2026 it was a hassle.First you have to remove the libssl1.1 dep from:My bash script (that\u2019s added below) will open the \u2018nano\u2019 editor and offer you to edit the control file specifying the deps. Your are looking for a line like this (starting with \u201cDepends\u201d and containing a reference to \u201clibssl1.1\u201d):Remove the reference to libssl1.1 and save & quit. It should look like this:The script will automagically repackage the files and generate you a new package with \u2018-newpackage.deb\u2019 attached to its name:Now put them in a folder and install them manually with dpkg:After that run:Hint: You don\u2019t need \u2018mongodb-mongosh\u2019 from the deps as it\u2019s being replaced by \u2018mongodb-mongosh-shared-openssl3\u2019.Afterwards I couldn\u2019t start the mongod service:Which was because of a missing user (after looking at \u2018/etc/systemd/system/mongod.service\u2019), so I added it:Edit, try, fail, repeat:Missing libcrypto from ssl 1.1\u2026I didn\u2019t have the 3.0 on the system, fix that:Now search for the file:link it:And we got the same error for ssl1.1\u2026Search, link, start\u2026And error (obviously - it\u2019s 3.0, not 1.1\u2026):But didn\u2019t I see a snap with 1.1 libs on the system when running the find commands? - Sure did!Let\u2019s remove the previous link and they those\u2026SUCCESS:Script:\nCode:\nmongodb-org-mongos_5.0.9_amd64.deb\n\nmongodb-org-server_5.0.9_amd64.deb\n\nmongodb-org-shell_5.0.9_amd64.deb\n\n\nDepends: libc6 (>= 2.29), libcurl4 (>= 7.16.2), libgcc-s1 (>= 4.2), liblzma5 (>= 5.1.1alpha+20110809), libssl1.1 (>= 1.1.1)\n\n\nDepends: libc6 (>= 2.29), libcurl4 (>= 7.16.2), libgcc-s1 (>= 4.2), liblzma5 (>= 5.1.1alpha+20110809)\n\n\nmongodb-org-mongos_5.0.9_amd64.deb-newpackage.deb\n\nmongodb-org-server_5.0.9_amd64.deb-newpackage.deb\n\nmongodb-org-shell_5.0.9_amd64.deb-newpackage.deb\n\n\nsudo dpkg -i *.deb\n\n\nsudo apt install --no-install-recommends mongodb-org mongodb-org-database mongodb-org-tools mongodb-mongosh-shared-openssl3\n\n\nJun 11 18:14:11 systemd[1]: Started MongoDB Database Server.\n\nJun 11 18:14:11 systemd[48437]: mongod.service: Failed to determine user credentials: No such process\n\nJun 11 18:14:11 systemd[48437]: mongod.service: Failed at step USER spawning /usr/bin/mongod: No such process\n\nJun 11 18:14:11 systemd[1]: mongod.service: Main process exited, code=exited, status=217/USER\n\nJun 11 18:14:11 systemd[1]: mongod.service: Failed with result 'exit-code'.\n\n\nsudo adduser mongodb\n\n\nJun 11 18:15:53 systemd[1]: Started MongoDB Database Server.\n\nJun 11 18:15:53 mongod[48504]: /usr/bin/mongod: error while loading shared libraries: libcrypto.so.1.1: cannot open shared object file: No such file or directory\n\nJun 11 18:15:53 systemd[1]: mongod.service: Main process exited, code=exited, status=127/n/a\n\nJun 11 18:15:53 systemd[1]: mongod.service: Failed with result 'exit-code'.\n\n\nsudo apt-get install libssl-dev\n\n\nsudo find / -type f -name libcrypto.so*\n\n\nsudo ln -s /usr/lib/x86_64-linux-gnu/libcrypto.so.3 /usr/lib/x86_64-linux-gnu/libcrypto.so.3 /usr/lib/x86_64-linux-gnu/libcrypto.so.1.1\n\n\nJun 11 18:23:59 mongod[48822]: /usr/bin/mongod: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory\n\n\nsudo find / -type f -name libssl.so.*\n\n\nsudo ln -s /usr/lib/x86_64-linux-gnu/libssl.so.3 /usr/lib/x86_64-linux-gnu/libssl.so.1.1\n\n\nJun 11 18:26:29 systemd[1]: Started MongoDB Database Server.\n\nJun 11 18:26:29 mongod[48845]: /usr/bin/mongod: /lib/x86_64-linux-gnu/libcrypto.so.1.1: version `OPENSSL_1_1_0' not found (required by /usr/bin/mongod)\n\nJun 11 18:26:29 mongod[48845]: /usr/bin/mongod: /lib/x86_64-linux-gnu/libssl.so.1.1: version `OPENSSL_1_1_0' not found (required by /usr/bin/mongod)\n\nJun 11 18:26:29 mongod[48845]: /usr/bin/mongod: /lib/x86_64-linux-gnu/libssl.so.1.1: version `OPENSSL_1_1_1' not found (required by /usr/bin/mongod)\n\n\n$ sudo find / -type f -name libcrypto.so*\n\n/usr/lib/x86_64-linux-gnu/libcrypto.so.3\n\n/snap/core20/1518/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1\n\n\n$ sudo find / -type f -name libssl.so.*\n\n/usr/lib/x86_64-linux-gnu/libssl.so.3\n\n/snap/core20/1518/usr/lib/x86_64-linux-gnu/libssl.so.1.1\n\n\n$ sudo rm /usr/lib/x86_64-linux-gnu/libcrypto.so.1.1 /usr/lib/x86_64-linux-gnu/libssl.so.1.1\n\n$ sudo ln -s /snap/core20/1518/usr/lib/x86_64-linux-gnu/libssl.so.1.1 /usr/lib/x86_64-linux-gnu/libssl.so.1.1\n\n$ sudo ln -s /snap/core20/1518/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1 /usr/lib/x86_64-linux-gnu/libcrypto.so.1.1\n\n\n$ sudo service mongod start && sudo service mongod status\n\n\u25cf mongod.service - MongoDB Database Server\n\nLoaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)\n\nActive: active (running) since Sat 2022-06-11 18:32:20 CEST; 49ms ago\n\nDocs: https://docs.mongodb.org/manual\n\nMain PID: 48894 (mongod)\n\nMemory: 760.0K\n\nCPU: 16ms\n\nCGroup: /system.slice/mongod.service\n\n\u2514\u250048894 /usr/bin/mongod --config /etc/mongod.conf\n\nJun 11 18:32:20 systemd[1]: Started MongoDB Database Server.\n#!/bin/bash\n# name: debedit.sh\n# author: showp1984\n# description: unpacks, edits control file and repacks deb-files with gz or xz compression\n# prerequisites: xz-utils && nano\n# No guarantees. Use at your own peril.\n\nunset DECOMPXZ\nunset DECOMPGZ\nFILES=\"{post,pre}{inst,rm} conffiles md5sums control\"\n\necho \"Uncompressing deb...\"\nar x $*\n\nFILEXZ=\"control.tar.xz\"\nif [ -f \"$FILEXZ\" ]; then\n DECOMPXZ=1\n echo \"Found: $FILEXZ | using XZ decomp...\"\n tar --xz -xvf $FILEXZ\nfi\n\nFILEGZ=\"control.tar.gz\"\nif [ -f \"$FILEGZ\" ]; then\n DECOMPGZ=1\n echo \"$FILEGZ exists.\"\n tar xzf $FILEGZ\nfi\n\nnano control\n\nif [[ \"$DECOMPXZ\" == 1 ]]; then\n echo \"Repacking $FILEXZ...\"\n tar --ignore-failed-read -cvJf $FILEXZ $FILES\n\n echo \"Repacking deb with xz files...\"\n ar rcs \"${*}-newpackage.deb\" debian-binary $FILEXZ data.tar.xz\nfi\n\nif [[ \"$DECOMPGZ\" == 1 ]]; then\n echo \"Repacking $FILEGZ...\"\n tar --ignore-failed-read -cvzf $FILEGZ $FILES\n\n echo \"Repacking deb with gz files...\"\n ar rcs \"${*}-newpackage.deb\" debian-binary $FILEGZ data.tar.gz\nfi\n\necho \"Cleanup...\"\nrm -r control md5sums debian-binary control.tar.xz data.tar.xz control.tar.gz data.tar.gz postrm preinst prerm conffiles postinst\n\necho \"Done!\"\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to use and format the TIMESTAMP in javascript? and tags: ['crud']"}, {"role": "user", "content": "Text:I\u2019m trying to work with the TIMESTAMP\u2026 I\u2019m posting here because I can\u2019t find ANY documentation or examples online or this site. If anybody knows any documentation that would be great!I\u2019m using MongoDB is a basic CMS, for like blog posts. I\u2019m saving created and edited TIMESTAMPS for each post. I have some mongoDB web hook functions that expose these posts to an API, making a headless CMS. The CMS works great, but those timestamps look like:Questions:I want to both display these in useful way in the blog post headers and order by them. What is the best way to format this? How do I do it? I think I\u2019d prefer formatting api side, but I\u2019m open to whatever.I know the ObjectId contains the created date somehow, is it more standard to use that somehow?I have triggers that format the blog posts\u2026 how do I automatically stamp the edited?I\u2019m not super opinionated on this, what\u2019s the easiest standard way to work with and format TIMESTAMPs with mongodb?Thanks for any help!General question: I always find MongoDB documentation and community very frustrating. Just trying to do basic thing, like format a timestamp, on other platforms I can find examples and documentation in seconds. Why is it so difficult with MongoDB? What am I doing wrong?Is there a Discord for MongoDB?\nCode:creatededited \"created\": {\n \"$timestamp\": {\n \"t\": 1631414145,\n \"i\": 5\n }\n },\n \"edited\": {\n \"$timestamp\": {\n \"t\": 1631414145,\n \"i\": 6\n }\n },\nedited"}, {"role": "assistant", "content": "Text:I\u2019m using MongoDB is a basic CMS, for like blog posts. I\u2019m saving created and edited TIMESTAMPS for each post.I suggest save the created and edited time fields as Date data type (instead of Timestamp type).For example,\nCode:creatededitedcreatededitedTimestampvar createdDt = new Date()\ndb.posts.insertOne({ title: \"Working with dates\", created: createdDt })\ndb.posts.findOne()\n// returns\n{\n \"_id\" : ObjectId(\"619474dd9043453a52147dd7\"),\n \"title\" : \"Working with dates\",\n \"created\" : ISODate(\"2021-11-17T03:19:56.186Z\")\n}\n"}, {"role": "user", "content": "Text:Thanks!Date() itself serialized as a similar useless object to TIMESTAMP. But storing this post.edited = new Date().toJSON(); creates that more meaningful iso date strong\u2026 with presumably I can work with on the frontend.I think this approach will work for me for now\u2026 is this standard?\nCode:post.edited = new Date().toJSON();"}, {"role": "assistant", "content": "Text:\u2026 is this standard?I think it is not. MongoDB data allows storing date as a date type. It is efficient storage, can be converted to any other forms (e.g., to string), has all the date/time related information, can be used for searching and sorting (compare with other dates), extract and use the different date fields (day, month, year, hour, min, sec, etc.) from it, perform date arithmetic, etc. All these operations can be applied using various query or aggregation operators (see Date Expression Operators).\nCode:date"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: com.mongodb.MongoNodeIsRecoveringException: Command failed with error 11600 (InterruptedAtShutdown) and tags: ['sharding']"}, {"role": "user", "content": "Text:we have a 6 Shards Cluster with 3 routers and 1 config replica set, we started getting below error when connecting from Routers, couldnt find any specific issue related to the cluster, i can see cluster available up and running, and issue seems intermittentcom.mongodb.MongoNodeIsRecoveringException: Command failed with error 11600 (InterruptedAtShutdown): \u2018interrupted at shutdown\u2019 on server XXX:XXX. The full response is {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"ok\": 0.0, \u201cerrmsg\u201d: \u201cinterrupted at shutdown\u201d, \u201ccode\u201d: 11600, \u201ccodeName\u201d: \u201cInterruptedAtShutdown\u201d, \u201coperationTime\u201d: {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"$timestamp\": {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"t\": 88608, \u201ci\u201d: 2}\u200b\u200b\u200b\u200b\u200b\u200b\u200b}\u200b\u200b\u200b\u200b\u200b\u200b\u200b, \u201c$clusterTime\u201d: {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"clusterTime\": {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"$timestamp\": {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"t\": 88608, \u201ci\u201d: 2}\u200b\u200b\u200b\u200b\u200b\u200b\u200b}\u200b\u200b\u200b\u200b\u200b\u200b\u200b, \u201csignature\u201d: {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"hash\": {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"$binary\": {\u200b\u200b\u200b\u200b\u200b\u200b\u200b\"base64\": \u201cXXXXXXXXXXXX\u201d, \u201csubType\u201d: \u201c00\u201d}\u200b\u200b\u200b\u200b\u200b\u200b\u200b}\u200b\u200b\u200b\u200b\u200b\u200b\u200b, \u201ckeyId\u201d: XXXXXXXXXXXXXX}\u200b\u200b\u200b\u200b\u200b\u200b\u200b}\u200b\u200b\u200b\u200b\u200b\u200b\u200b}\u200b\u200b\u200b\u200b\u200b\u200b\u200b at com.mongodb.internal.connection.ProtocolHelper.createSpecialException(ProtocolHelper.java:242) ~[mongodb-driver-core-4.1.1.jar:na] at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:171) ~[mongodb-driver-core-4.1.1.jar:na] at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:359) ~[mongodb-driver-core-4.1.1.jar:na] at com.mongodb.internal.connection.InternalStreamConnection.receive(InternalStreamConnection.java:316) ~[mongodb-driver-core-4.1.1.jar:na] at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.lookupServerDescription(DefaultServerMonitor.java:215) ~[mongodb-driver-core-4.1.1.jar:na] at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:144) ~[mongodb-driver-core-4.1.1.jar:na] at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]\nCode:"}, {"role": "assistant", "content": "Text:Hi @Bhaskar_Avisha\nFirst of all, welcome to MongoDB Community Forum\u2026 Command failed with error 11600 (InterruptedAtShutdown):I believe error 11600 means that the client is trying to do an operation on a server that is shutting down.So, if you provide the driver with a connection URI that specifies a replica set, the driver should reconnect to the new primary as soon as it\u2019s available. See Connection String URI Format, specifically the replica set option section.I hope it works for you.\nLet us know if it or still persists.In case of any doubts please feel free to reach out.Regards,\nKushagra\nCode:"}, {"role": "user", "content": "Text:Thanks @Kushagra_KesavI am getting this error , when application is connecting through mongos , this is not a direct connection to replica set.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Bhaskar_Avisha,As far as I can tell, the com.mongodb.MongoNodeIsRecoveringException is a possible error that happens when you\u2019re connected to a replica set. From the linked page:An exception indicating that the server is a member of a replica set but is in recovery mode, and therefore refused to execute the operation. This can happen when a server is starting up and trying to join the replica set.However I don\u2019t think there\u2019s enough information here to determine what\u2019s going on. Could you post more details:Best regards,\nKevin\nCode:mongosmongo"}, {"role": "assistant", "content": "Text:Hi @Bhaskar_Avisha, have you got your issue resolved?\nWe\u2019re facing a similar problem, our client application keeps loosing the connection to the Atlas cluster and since we are using tailable cursors, our app has to restart upon each interruption which is highly annoying.\nThe client connects to the cluster via \u2018mongodb+srv://\u2019 URL\nCode: Jan 10 23:20:10 ip-***.eu-west-1.compute.internal [cluster-ClusterId{value='61dc9f7a153a5d03282359a1', description='null'}-demo-shard-00-01.l76nh.mongodb.net:27017] WARN c.g.r.c.config.MongoDbConfiguration: MongoDB serverHeartbeatFailed: ServerHeartbeatFailedEvent{connectionId=connectionId{localValue:12, serverValue:269}, elapsedTimeNanos=950823445, awaited=true, throwable=com.mongodb.MongoNodeIsRecoveringException: Command failed with error 11600 (InterruptedAtShutdown): 'interrupted at shutdown' on server ***.l76nh.mongodb.net:27017. The full response is {\"operationTime\": {\"$timestamp\": {\"t\": 1641853208, \"i\": 11}}, \"ok\": 0.0, \"errmsg\": \"interrupted at shutdown\", \"code\": 11600, \"codeName\": \"InterruptedAtShutdown\", \"$clusterTime\": {\"clusterTime\": {\"$timestamp\": {\"t\": 1641853208, \"i\": 15}}, \"signature\": {\"hash\": {\"$binary\": {\"base64\": \"5cTlPKELM4icjdNscfA1g85B75s=\", \"subType\": \"00\"}}, \"keyId\": 7006031879656701953}}}} com.mongodb.event.ServerHeartbeatFailedEvent@583a7488\nJan 10 23:20:10 ip-***.eu-west-1.compute.internal org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 11600 and error message 'interrupted at shutdown' on server demo-shard-00-01.l76nh.mongodb.net:27017; nested exception is com.mongodb.MongoQueryException: Query failed with error code 11600 and error message 'interrupted at shutdown' on server ***.l76nh.mongodb.net:27017\n \tat org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:140)\n \tat org.springframework.data.mongodb.core.ReactiveMongoTemplate.potentiallyConvertRuntimeException(ReactiveMongoTemplate.java:2814)\n \tat org.springframework.data.mongodb.core.ReactiveMongoTemplate.lambda$translateException$90(ReactiveMongoTemplate.java:2797)\n \tat reactor.core.publisher.Flux.lambda$onErrorMap$28(Flux.java:6910)\n \tat reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94)\n"}, {"role": "assistant", "content": "Text:Hi, everyone!\nWe also encountered this problem while upgrading our MongoDB shard cluster from 4.0.12 to 4.2.17.\nDuring the upgrade we were observing this kind of error messages in our logs(I edited out the collection names, filters, signature, and router names.)The upgrade process was as follows:As we observed, the aforementioned errors were showing up right after stopping the process. And also we saw the errors while connecting with ReadPreference = Primary and \t\t\t\tReadPreference = SecondaryPreferred.To answer @kevinadi questions:What we want to know is how to upgrade a MongoDB shard cluster more flawlessly. Any advice is really appreciated.\nCode:Code: 11600;\nCodeName: InterruptedAtShutdown;\nCommand: { \"getMore\" : NumberLong(\"9001353061637322596\"), \"collection\" : \"some.collection\" };\nErrorMessage: interrupted at shutdown;\nResult: { \"ok\" : 0.0, \"errmsg\" : \"interrupted at shutdown\", \"code\" : 11600, \"codeName\" : \"InterruptedAtShutdown\" };\nConnectionId: { ServerId : { ClusterId : 1, EndPoint : \"Unspecified/some.router.name:27017\" }, LocalValue : 290 };\nErrorLabels: System.Collections.Generic.List`1[System.String]\n\nMongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11600, codeName = \"InterruptedAtShutdown\").\n at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol`1.ProcessResponse(ConnectionId connectionId, CommandMessage responseMessage)\n at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocol[TResult](IWireProtocol`1 protocol, ICoreSession session, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Servers.Server.ServerChannel.Command[TResult](ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, IEnumerable`1 commandPayloads, IElementNameValidator commandValidator, BsonDocument additionalOptions, Action`1 postWriteAction, CommandResponseHandling responseHandling, IBsonSerializer`1 resultSerializer, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.AsyncCursor`1.ExecuteGetMoreCommand(IChannelHandle channel, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.AsyncCursor`1.GetNextBatch(CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.AsyncCursor`1.MoveNext(CancellationToken cancellationToken)\n at MongoDB.Driver.IAsyncCursorExtensions.ToList[TDocument](IAsyncCursor`1 source, CancellationToken cancellationToken)\n at MongoDB.Driver.IAsyncCursorSourceExtensions.ToList[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)\nCode: 11600;\nCodeName: InterruptedAtShutdown;\nCommand: { \"find\" : \"some.collection\", \"filter\" : {somefilter} };\nErrorMessage: Encountered non-retryable error during query :: caused by :: interrupted at shutdown;\nResult: { \"ok\" : 0.0, \"errmsg\" : \"Encountered non-retryable error during query :: caused by :: interrupted at shutdown\", \"code\" : 11600, \"codeName\" : \"InterruptedAtShutdown\", \"operationTime\" : Timestamp(1642587846, 583), \"$clusterTime\" : { \"clusterTime\" : Timestamp(1642587850, 1385), \"signature\" : { \"some signature\" } } };\nConnectionId: { ServerId : { ClusterId : 2, EndPoint : \"Unspecified/some.router.name:27017\" }, LocalValue : 4228 };\nErrorLabels: System.Collections.Generic.List`1[System.String]\n\nMongoDB.Driver.MongoNodeIsRecoveringException: Server returned node is recovering error (code = 11600, codeName = \"InterruptedAtShutdown\").\n at MongoDB.Driver.Core.Operations.RetryableReadOperationExecutor.ExecuteAsync[TResult](IRetryableReadOperation`1 operation, RetryableReadContext context, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.ReadCommandOperation`1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.FindCommandOperation`1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)\n at MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)\n at MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)\n at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)\nsystemctl stop mongodsystemctl stop mongosmongodmongosReadPreference = Primary\t\t\t\tReadPreference = SecondaryPreferred4.0.122.11.4\t\t\tvar settings = new MongoClientSettings\n\t\t\t{\n\t\t\t\tServers = \"{router names}\",\n\t\t\t\tConnectionMode = ConnectionMode.Automatic,\n\t\t\t\tMaxConnectionIdleTime = TimeSpan.FromMinutes(10),\n\t\t\t\tMaxConnectionLifeTime = TimeSpan.FromMinutes(30),\n\t\t\t\tMaxConnectionPoolSize = 100,\n\t\t\t\tMinConnectionPoolSize = 1,\n\t\t\t\tReadPreference = ReadPreference.Primary, // and could be SecondaryPreferred\n\t\t\t\tSocketTimeout = TimeSpan.Zero,\n\t\t\t\tWaitQueueTimeout = TimeSpan.FromMinutes(2),\n\t\t\t\tWriteConcern = WriteConcern.W1,\n\t\t\t\tConnectTimeout = TimeSpan.FromSeconds(15),\n\t\t\t\tReadConcern = ReadConcern.Default,\n\t\t\t\tServerSelectionTimeout = TimeSpan.FromSeconds(15),\n\t\t\t};\n\nmongo"}, {"role": "assistant", "content": "Text:We\u2019re running into this same issue while doing a rolling upgrade from 4.0 \u2192 4.2 .\nAll clients are running java.Any updates or solutions available?\nThanks,\nTom\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoDB.Driver.MongoConnectionException: An exception occurred while sending a message to the server and tags: []"}, {"role": "user", "content": "Text:I got below exception while try to update data in mongodb. Please help me to fix this issue.When I look in my logs I see lot of error messages just like the one below where the driver is getting a socket error when connecting to mongo. The site is still up and this error doesn\u2019t happen on every request, nor does it happen on one operation that should take longer.The version I have used C# driver : \u201c2.10.2\u201d and Azure Cosmos version :3.6\".Code that causes issue,\nCode:MongoDB.Driver.MongoConnectionException: An exception occurred while sending a message to the server. ---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host\n at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)\n at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)\n --- End of inner exception stack trace ---\n at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)\n at System.Net.Security._SslStream.StartWriting(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)\n at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)\n at System.Net.Security.SslStream.Write(Byte[] buffer, Int32 offset, Int32 count)\n at MongoDB.Driver.Core.Misc.StreamExtensionMethods.WriteBytes(Stream stream, IByteBuffer buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Connections.BinaryConnection.SendBuffer(IByteBuffer buffer, CancellationToken cancellationToken)\n --- End of inner exception stack trace ---\n at MongoDB.Driver.Core.Connections.BinaryConnection.SendBuffer(IByteBuffer buffer, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Connections.BinaryConnection.SendMessages(IEnumerable`1 messages, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.ConnectionPools.ExclusiveConnectionPool.AcquiredConnection.SendMessages(IEnumerable`1 messages, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Connections.ConnectionExtensions.SendMessage(IConnection connection, RequestMessage message, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.WireProtocol.CommandUsingCommandMessageWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.WireProtocol.CommandWireProtocol`1.Execute(IConnection connection, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Servers.Server.ServerChannel.ExecuteProtocol[TResult](IWireProtocol`1 protocol, ICoreSession session, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Servers.Server.ServerChannel.Command[TResult](ICoreSession session, ReadPreference readPreference, DatabaseNamespace databaseNamespace, BsonDocument command, IEnumerable`1 commandPayloads, IElementNameValidator commandValidator, BsonDocument additionalOptions, Action`1 postWriteAction, CommandResponseHandling responseHandling, IBsonSerializer`1 resultSerializer, MessageEncoderSettings messageEncoderSettings, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.RetryableWriteCommandOperationBase.ExecuteAttempt(RetryableWriteContext context, Int32 attempt, Nullable`1 transactionNumber, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.RetryableWriteOperationExecutor.Execute[TResult](IRetryableWriteOperation`1 operation, RetryableWriteContext context, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.ExecuteBatches(RetryableWriteContext context, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.BulkUnmixedWriteOperationBase`1.Execute(RetryableWriteContext context, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken)\n at MongoDB.Driver.Core.Operations.BulkMixedWriteOperation.Execute(IWriteBinding binding, CancellationToken cancellationToken)\n at MongoDB.Driver.OperationExecutor.ExecuteWriteOperation[TResult](IWriteBinding binding, IWriteOperation`1 operation, CancellationToken cancellationToken)\n at MongoDB.Driver.MongoCollectionImpl`1.ExecuteWriteOperation[TResult](IClientSessionHandle session, IWriteOperation`1 operation, CancellationToken cancellationToken)\n at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IClientSessionHandle session, IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)\n at MongoDB.Driver.MongoCollectionImpl`1.<>c__DisplayClass23_0.b__0(IClientSessionHandle session)\n at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSession[TResult](Func`2 func, CancellationToken cancellationToken)\n at MongoDB.Driver.MongoCollectionImpl`1.BulkWrite(IEnumerable`1 requests, BulkWriteOptions options, CancellationToken cancellationToken)\n at MongoDB.Driver.MongoCollectionBase`1.<>c__DisplayClass92_0.b__0(IEnumerable`1 requests, BulkWriteOptions bulkWriteOptions)\n at MongoDB.Driver.MongoCollectionBase`1.UpdateMany(FilterDefinition`1 filter, UpdateDefinition`1 update, UpdateOptions options, Func`3 bulkWrite)\n at MongoDB.Driver.MongoCollectionBase`1.UpdateMany(FilterDefinition`1 filter, UpdateDefinition`1 update, UpdateOptions options, CancellationToken cancellationToken)\n at Sensiple.Tryvium.Data.MongoDB.CommonConnector.Update(String schemaName, String dataFilter, String data, String logSource) \nvar _collection = Db.GetCollection(schemaName); \n\nBsonDocument bsonDocument = new BsonDocument(BsonSerializer.Deserialize(dataFilter)); \n\nvar updatedResult = _collection.UpdateMany(bsonDocument, BsonDocument.Parse(\"{$set: \" + BsonSerializer.Deserialize(data) + \"}\"));\n"}, {"role": "assistant", "content": "Text:Hi,The version I have used C# driver : \u201c2.10.2\u201d and Azure Cosmos version :3.6\".It appears that you are trying to connect to Azure Cosmos DB using the official MongoDB dotnet driver. Is this correct?If yes, then unfortunately this configuration is not supported since Cosmos DB is a Microsoft product that provides MongoDB compatibility, and thus it may time to time see some incompatibilities with official MongoDB drivers, which are designed for use with the official MongoDB server.Could you try the code on an official MongoDB server (e.g. a free MongoDB Atlas shared instance for testing purposes) and see if the error persists? If not, then you may want to contact Microsoft support regarding this issue.Best regards,\nKevin\nCode:"}, {"role": "assistant", "content": "Text:I\u2019ve had the exact same issue (using exact same driver version 2.10.2), and it started exactly after I\u2019ve upgraded from Cosmos 3.2 to 3.6 (also happens with 4.0) and the issue was solved by forcing TLS 1.2var settings = MongoClientSettings.FromConnectionString(connectionString);\nsettings.SslSettings = new SslSettings()\n{\nEnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12\n};\nreturn new MongoClient(settings);\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Ubuntu 22.04 and mssing libcrypto.so.1.1 and tags: []"}, {"role": "user", "content": "Text:I\u2019m trying to use mongo shell on Ubuntu 22.04, but libcrypto.so.1.1 isn\u2019t available.That library doesn\u2019t exist in any package for Jammy:https://packages.ubuntu.com/search?suite=jammy&arch=any&mode=exactfilename&searchon=contents&keywords=libcrypto.so.1.1Is there a solution for this?\nCode:libcrypto.so.1.1mongodb-shell-linux-x86_64-ubuntu2004-5.0.9/mongodb-linux-x86_64-ubuntu2004-5.0.9$ ./bin/mongo 192.168.1.20:27017\n./bin/mongo: error while loading shared libraries: libcrypto.so.1.1: cannot open shared object file: No such file or directory\n"}, {"role": "assistant", "content": "Text:mongosh is available as a PPA for Ubuntu 20.04 (Focal) and Ubuntu 18.04 (Bionic).Wait for a package that supports 22.04.Run a container in the meantime ?\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Using MongoDB Atlas on Lambda throws Could not connect to any servers in MongoDB Atlas cluster error and tags: ['node-js', 'mongoose-odm', 'serverless']"}, {"role": "user", "content": "Text:I am using node lambda which is a api server that accepts request from API gateway. The lambda connects to mongo db atlas to pull data from the db and then returns it in the response. For the most part it works fine with no issues but randomly it runs into mongo atlas connection errors:My mongo DB atlas instance allows ip addresses from everywhere: 0.0.0.0.This is how I am making my mongo connection:I am also using mongoose version 5.12.8\nCode: {\n \"errorType\": \"Runtime.UnhandledPromiseRejection\",\n \"errorMessage\": \"MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/\",\n \"reason\": {\n \"errorType\": \"MongooseServerSelectionError\",\n \"errorMessage\": \"Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/\",\n \"message\": \"Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/\",\n \"reason\": {\n \"type\": \"ReplicaSetNoPrimary\",\n \"setName\": null,\n \"maxSetVersion\": null,\n \"maxElectionId\": null,\n \"servers\": {},\n \"stale\": false,\n \"compatible\": true,\n \"compatibilityError\": null,\n \"logicalSessionTimeoutMinutes\": null,\n \"heartbeatFrequencyMS\": 10000,\n \"localThresholdMS\": 15,\n \"commonWireVersion\": null\n },\n \"stack\": [\n \"MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/\",\n \" at NativeConnection.Connection.openUri (/var/task/node_modules/mongoose/lib/connection.js:846:32)\",\n \" at /var/task/node_modules/mongoose/lib/index.js:351:10\",\n \" at /var/task/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5\",\n \" at new Promise ()\",\n \" at promiseOrCallback (/var/task/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)\",\n \" at Mongoose._promiseOrCallback (/var/task/node_modules/mongoose/lib/index.js:1149:10)\",\n \" at Mongoose.connect (/var/task/node_modules/mongoose/lib/index.js:350:20)\",\n \" at Object. (/var/task/build/app.js:172:40)\",\n \" at Module._compile (internal/modules/cjs/loader.js:999:30)\",\n \" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)\",\n \" at Module.load (internal/modules/cjs/loader.js:863:32)\",\n \" at Function.Module._load (internal/modules/cjs/loader.js:708:14)\",\n \" at Module.require (internal/modules/cjs/loader.js:887:19)\",\n \" at require (internal/modules/cjs/helpers.js:74:18)\",\n \" at _tryRequire (/var/runtime/UserFunction.js:75:12)\",\n \" at _loadUserApp (/var/runtime/UserFunction.js:95:12)\"\n ]\n },\n \"promise\": {},\n \"stack\": [\n \"Runtime.UnhandledPromiseRejection: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/\",\n \" at process. (/var/runtime/index.js:35:15)\",\n \" at process.emit (events.js:314:20)\",\n \" at process.EventEmitter.emit (domain.js:483:12)\",\n \" at processPromiseRejections (internal/process/promises.js:209:33)\",\n \" at processTicksAndRejections (internal/process/task_queues.js:98:32)\"\n ]\n}\nimport express from \"express\";\nimport serverless from \"serverless-http\";\nimport mongoose, { Error } from \"mongoose\";\nimport { APIGatewayProxyHandler } from 'aws-lambda';\nimport { AppSettings } from \"./constants/constants\";\n\nclass App {\n\n public app: express.Application;\n public mongoUrl: string = AppSettings.MONGODBURL;\n\n constructor() {\n this.setupDBConn();\n }\n async setupDBConn() {\n this.app = express();\n }\n\n private async mongoSetup() {\n await mongoClient;\n console.log('MONGO connection successfully made...');\n }\n}\nconst mongoClient = mongoose.connect(AppSettings.MONGODBURL, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false });\nexport const handler: APIGatewayProxyHandler = serverless(new App().app);\n"}, {"role": "assistant", "content": "Text:Hi @Shawn_Varughese and welcome in the MongoDB Community !Are you creating a new connection (==mongoClient) for each Lambda or your MongoDB Connections are shared across multiple (all) lambdas?I give you a little hint, \u201cyes\u201d is a very bad answer !Check out this doc where they explain how to set up the connection correctly:Using a private endpoint would also be a plus (instead of 0.0.0.0/0).Cheers,\nMaxime.\nCode:"}, {"role": "user", "content": "Text:Thanks for this and this is helpful I did go through this and we do have the connection outside the lambda function and the connection is shared in the code we have the mongoClient outside the App class and the serverless function just waits for the mongo connection and reuses it. Unfortunately we are still seeing this connection issue.Any other ideas on why we might be seeing this?\nCode:"}, {"role": "assistant", "content": "Text:I don\u2019t understand why you would get this error if the connection was already established and functional and if your cluster is healthy on the other hand. This error message makes me think that the connection is being created at that moment.If it\u2019s really an occasional error, maybe this is happening when you have a maintenance on the cluster? Can you link this to an event in Atlas?\nBut in theory, it\u2019s supposed to be transparent for the clients, unless something is misconfigured.\nCode:"}, {"role": "user", "content": "Text:Interesting I am not sure that could be possible. I dont see any open alerts in Atlas is that what you were asking for? To give you more context our platform is microservices based so we have 8 microservices which are all separate lambda functions and each connect to atlas to read/write to the database.You dont see this as a problem right?\nCode:"}, {"role": "assistant", "content": "Text:I dont see any open alerts in Atlas is that what you were asking for?Yes. Then it\u2019s something else.You dont see this as a problem right?No, sounds like I would do exactly the same thing. Given that your connection pool is centralised and reused correctly by all the lambdas, maybe you could increase the size of the pool? If you have many lambdas running in parallel, I guess you need a connection pool large enough to accommodate all the queries.\nCode:"}, {"role": "user", "content": "Text:So are you all 8 microservices should share the same connection pool? How would i be able to do that if they are all separate lambda functionsOr each lambda function shares its own connection pool and just does not create a new connection each invocation?\nCode:"}, {"role": "assistant", "content": "Text:Ado proposed an implementation here based on a cache:Learn how to write serverless functions with AWS Lambda and MongoDBIt\u2019s fine if you use like 8 different pools as long as it\u2019s a small number, it\u2019s OK. What\u2019s not OK is one connection to the cluster per lambda execution. That\u2019s definitely a problem.Your cluster can only support a limited number of connections. For an M10 it\u2019s 1500 per node for example.https://www.mongodb.com/docs/atlas/reference/atlas-limits/.Keep an eye on the monitoring to see if you are getting close to that limit.Cheers,\nMaxime.\nCode:"}, {"role": "user", "content": "Text:Thanks for this i was able to implementing the caching and it seems like it working well so far! Now after implementing caching i am facing a new error:This doesn\u2019t happen all the time just randomly I assume its because the cached db connection has timed out. Any advise here?\nCode:ERROR\tUnhandled Promise Rejection \t{\n \"errorType\": \"Runtime.UnhandledPromiseRejection\",\n \"errorMessage\": \"MongoNetworkTimeoutError: connection timed out\",\n \"reason\": {\n \"errorType\": \"MongoNetworkTimeoutError\",\n \"errorMessage\": \"connection timed out\",\n \"name\": \"MongoNetworkTimeoutError\",\n \"stack\": [\n \"MongoNetworkTimeoutError: connection timed out\",\n \" at connectionFailureError (/var/task/node_modules/mongodb/lib/core/connection/connect.js:362:14)\",\n \" at TLSSocket. (/var/task/node_modules/mongodb/lib/core/connection/connect.js:330:16)\",\n \" at Object.onceWrapper (events.js:420:28)\",\n \" at TLSSocket.emit (events.js:314:20)\",\n \" at TLSSocket.EventEmitter.emit (domain.js:483:12)\",\n \" at TLSSocket.Socket._onTimeout (net.js:483:8)\",\n \" at listOnTimeout (internal/timers.js:554:17)\",\n \" at processTimers (internal/timers.js:497:7)\"\n ]\n },\n \"promise\": {},\n \"stack\": [\n \"Runtime.UnhandledPromiseRejection: MongoNetworkTimeoutError: connection timed out\",\n \" at /var/runtime/index.js:35:15\",\n \" at /opt/nodejs/node_modules/@lumigo/tracer/dist/tracer/tracer.js:265:37\",\n \" at processTicksAndRejections (internal/process/task_queues.js:97:5)\"\n ]\n}\n"}, {"role": "user", "content": "Text:@MaBeuLux88 any thoughts on this error i am getting now after implementing the cacheing?\nCode:"}, {"role": "assistant", "content": "Text:Hey @Shawn_Varughese,So sorry for the terrible delay to answer. I had a baby on May 1st so I was a little distracted.To be honest, I have no idea at all. If it\u2019s happening \u201crandomly\u201d, is this happening maybe after your lambda wasn\u2019t triggered for a long time?What timeout have your defined? Did you try to increase them a bit so maybe this gives more opportunity for this connection to land?Search for \u201ctimeout\u201d in here and try to increase the relevant one maybe? I assume connectTimeoutMS here, no?Cheers,\nMaxime.\nCode:connectTimeoutMS"}, {"role": "user", "content": "Text:@MaBeuLux88 ,Not a problem at all congratulations on your baby!!!Yeah I tried changing socketTimeout but that did not seem to help. Do you think the connectTimeout might be better? I am stumped on whats causing this.\nCode:"}, {"role": "assistant", "content": "Text:Thanks !connectTimeout would only apply to the very first connection that is then cached for later use by the lambdas. So I think this isn\u2019t the one you are looking for but\u2026 Give it a try?Cheers,\nMaxime.\nCode:connectTimeout"}, {"role": "assistant", "content": "Text:We\u2019ve been suffering from the exact same problem - occasional timeouts on connection to Mongo from AWS Lambda. It feels like an event / issue occurring on the MongoDb / Atlas instance - but nothing in the Atlas event log to indicate as such.Our lambda timeout is being hit at 60 seconds - but basically Atlas is just not giving a connection - without error other than via connection timeout.We work in c# and are establishing our MongoClient connections via DI - ie outside of each method function call - just on initialisation.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Stewart_Snow and welcome in the MongoDB Community !Did you try to add some options to the C# driver connection like increase the timeouts, etc ? Maybe waitQueueTimeoutMS can help?Cheers,\nMaxime.\nCode:waitQueueTimeoutMS"}, {"role": "assistant", "content": "Text:https://www.mongodb.com/docs/manual/reference/connection-string/#connection-pool-optionsHey - we can try that - but it feels wrong. In this case the database that we\u2019re connecting to (running in Atlas) is absolutely tiny - barely 50kb of data. At max there is 10 connections open to it. It\u2019s just so small / lightweight that it really shouldn\u2019t be behaving as it is - it makes no sense.I can understand needing big timeouts - some sort of heavily load scenario\u2019s - but we\u2019re dealing with such a low-load scenario it\u2019s strange. Timing out at 60 seconds or so - just to get the connection to the DB seems very strange indeed.We\u2019re having a go at trying a slightly different pattern for the initialization of our mongo connection from our Lambda function to see if that makes any difference.\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m wondering if there is a limit to keep the connection alive if it\u2019s not used for a long time. Please let me know if you find a solution because I don\u2019t have a test environment up to test it at the moment.Also you read that one right?\nCode:"}, {"role": "assistant", "content": "Text:Will do - and yes aware of that doc - cheers!\nCode:"}, {"role": "assistant", "content": "Text:Okay - just following up here. We tweaked our initialisation code, so that we\u2019re 100% inline with mongo / lambda recommendations - but it\u2019s still producing the same issue on occasion.Each time it occurs we get two close errors:Error 1\nAn unhandled exception has occurred while executing the request.System.TimeoutException: A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode : Primary } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : \u201c1\u201d, ConnectionMode : \u201cReplicaSet\u201d, Type : \u201cReplicaSet\u201d, State : \u201cConnected\u201d, Servers : [{ ServerId: \u201c{ ClusterId : 1, EndPoint : \u201cUnspecified/XXXXXX\u201d }\u201d, EndPoint: \u201cUnspecified/XXXXXXX\u201d, ReasonChanged: \u201cHeartbeat\u201d, State: \u201cConnected\u201d, ServerVersion: 5.0.9, TopologyVersion: { \u201cprocessId\u201d : ObjectId(\u201c62aa3b6c7c78a0c51037b843\u201d), \u201ccounter\u201d : NumberLong(4) }, Type: \u201cReplicaSetSecondary\u201d, Tags: \u201c{ region : US_EAST_1, provider : AWS, nodeType : ELECTABLE, workloadType : OPERATIONAL }\u201d, WireVersionRange: \u201c[0, 13]\u201d, LastHeartbeatTimestamp: \u201c2022-06-27T10:25:32.0295404Z\u201d, LastUpdateTimestamp: \u201c2022-06-27T10:25:32.0295416Z\u201d }, { ServerId: \u201c{ ClusterId : 1, EndPoint : \u201cUnspecified/XXXXX\u201d }\u201d, EndPoint: \u201cUnspecified/XXXXXX\u201d, ReasonChanged: \u201cHeartbeat\u201d, State: \u201cDisconnected\u201d, ServerVersion: , TopologyVersion: , Type: \u201cUnknown\u201d, HeartbeatException: \"MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. \u2014> System.TimeoutException: Timed out connecting to X.X.X.X. Timeout was 00:00:30. at MongoDB.Driver.Core.Connections.TcpStreamFactory.ConnectAsync(Socket socket, EndPoint endPoint, CancellationToken cancellationToken) at MongoDB.Driver\u2026Error 2\n[Error] An unhandled exception has occurred while executing the request.MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. \u2014> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer. \u2014> System.Net.Sockets.SocketException (104): Connection reset by peer \u2014 End of inner exception stack trace \u2014 at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token) at System.Net.FixedSizeReader.ReadPacketAsync(Stream transport, AsyncProtocolRequest request) at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result) at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult) at System.Net.Security.SslStream.<>c.b__64_2(IAsyncResult iar) at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization)\u2014 End of stack trace from previous location where exception was thrownWe\u2019re using mongo+srv style connection string plus the following options:\nretryWrites=true&w=majority\u2026? We\u2019re at a loss - makes no sense. Any suggestions??\nCode:1.FromAsyncCoreLogic(IAsyncResult iar, Func1 endAction, Task"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 and tags: ['node-js', 'server', 'storage']"}, {"role": "user", "content": "Text:Hi, could you help me?\nI keep getting this error when I launch node app.js.\nMongo shell connects, service MongoDB running (win11), me desperate.This is the code, tested fine on other machines:My config file looks like this, tried all possible combinations of paths and optional\nCode:MongoServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017\n at Timeout._onTimeout (/.../node_modules/mongodb/lib/sdam/topology.js:293:38)\n at listOnTimeout (node:internal/timers:557:17)\n at processTimers (node:internal/timers:500:7) {\n reason: TopologyDescription {\n type: 'Unknown',\n servers: Map(1) { '127.0.0.1:27017' => [ServerDescription] },\n stale: false,\n compatible: true,\n heartbeatFrequencyMS: 10000,\n localThresholdMS: 15,\n setName: null,\n maxElectionId: null,\n maxSetVersion: null,\n commonWireVersion: 0,\n logicalSessionTimeoutMinutes: null\n },\n code: undefined,\n [Symbol(errorLabels)]: Set(0) {}\n}\nconst { MongoClient } = require(\"mongodb\");\n\nconst uri = \"mongodb://127.0.0.1:27017/\"\nconst client = new MongoClient(uri);\nasync function run() {\n try {\n const database = client.db('sample_mflix');\n const movies = database.collection('movies');\n // Query for a movie that has the title 'Back to the Future'\n const query = { title: 'Back to the Future' };\n const movie = await movies.findOne(query);\n console.log(movie);\n } finally {\n // Ensures that the client will close when you finish/error\n await client.close();\n }\n}\nrun().catch(console.dir);\n\nstorage:\n dbPath: C:\\data\\db\n journal:\n enabled: true\n# engine:\n# wiredTiger:\n\n# where to write logging data.\nsystemLog:\n destination: file\n logAppend: true\n path: C:\\Program Files\\MongoDB\\Server\\6.0\\log\\mongod.log\n\n# network interfaces\nnet:\n port: 27017\n bindIp: 127.0.0.1\n ipv6: true\n"}, {"role": "assistant", "content": "Text:Is your service up and running,?\nShow snapshot of your Windows service and shell connection you connected successfully\nCode:"}, {"role": "user", "content": "Text:\nScreenshot 2022-10-25 1307161109\u00d7673 155 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Issue could be bindIp parameter\nCheck this link for Ipv6\nCode:"}, {"role": "user", "content": "Text:This are the settings, I turned back on the bindIpAll optionI checked firewall and created rules for mongod/mongos, set the network to private, flushed the DNS.\nI have no idea what to do\nCode:net:\n port: 27017\n bindIp: 127.0.0.1\n ipv6: true\n bindIpAll: true\n"}, {"role": "assistant", "content": "Text:You cannot use both bindIp & bindIp_all at same time\nUse only one of them in your cfg file\nTry 0.0.0.0 for bind_ip (not adviced on prod) and see if it works\nCode:"}, {"role": "assistant", "content": "Text:Also check this for exact format for Ipv6 with localhost\nCode:"}, {"role": "user", "content": "Text:Thank you Ramachandra, but still nothing, I had the configuration suggested in the post you linked, now I have it like this, still nothing.I switched to node 19 (from 16), same with both versions. MongoDB v 6.0.2\nCode:net:\n port: 27017\n ipv6: true\n bindIpAll: true\n"}, {"role": "assistant", "content": "Text:Is your IP whitelisted?\nDid you try without Ipv6(use ipv4)\nor\nDon\u2019t use bindipall and try other format given for ipv6 with localhost,::\nIs your localhost mapped to 127.0.0.1?\nIs the machine where your node.app runs same as db server?\nCode:"}, {"role": "user", "content": "Text:My IP is whitelisted\nMy localhost goes like this in the hosts fileI tried all the options and combinations, still nothing.\nMongod runs as window service, but I also tried stopping the service and launching a mongod instance on the ubuntu terminal (what I use normally) and I have the same results. Mongosh connects but node app doesn\u2019t.\nCode:"}, {"role": "assistant", "content": "Text:If mongosh connect then your application should connect if you run your application on the same machine as mongosh. The following might indicates that you are using 2 machines or a VM:Mongod runs as window service, but I also tried stopping the service and launching a mongod instance on the ubuntu terminalIs the ubuntu terminal running on the same Windows where mongod is running as a service? When you connect with mongosh, do you connect from the same Windows machine where mongod is running? Is the app running on the same machine as the mongosh that can connect?You shared a couple of version of your configuration file. Please share the latest version. Have you restarted mongod after changing the configuration file?\nCode:"}, {"role": "user", "content": "Text:Yeah same machine. I run mongosh on WSL terminal and it connects (with windows service running AND if I stop that service and run an instance of mongod on WSL).The latest configuration file. Mind that I\u2019ve tried many combinations, this is from a MacOS where I tested and it worked fine.\nCode:"}, {"role": "assistant", "content": "Text:I am not clear\nHow can Macos have Windows directory paths?\nI have suggested in above posts to use 127.0.0.1,::1\nLet\u2019s wait for Steeves reply\nCode:"}, {"role": "user", "content": "Text:The directory path for mac is different of course, but that\u2019s not the point. Can it be something about windows security or similar?\nCode:"}, {"role": "assistant", "content": "Text:Share the content of the log.I would try without ipv6 true and without ::1 for bindIp, just to simplify things.\nCode:"}, {"role": "user", "content": "Text:\nCode:{\"t\":{\"$date\":\"2022-10-27T15:44:46.274+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23285, \"ctx\":\"-\",\"msg\":\"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'\"}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.112+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915701, \"ctx\":\"thread1\",\"msg\":\"Initialized wire specification\",\"attr\":{\"spec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"outgoing\":{\"minWireVersion\":6,\"maxWireVersion\":17},\"isInternalClient\":true}}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.113+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4648602, \"ctx\":\"thread1\",\"msg\":\"Implicit TCP FastOpen in use.\"}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.115+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationDonorService\",\"namespace\":\"config.tenantMigrationDonors\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.122+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"namespace\":\"config.tenantMigrationRecipients\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.122+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"ShardSplitDonorService\",\"namespace\":\"config.tenantSplitDonors\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.122+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"thread1\",\"msg\":\"Multi threading initialized\"}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.122+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23316, \"ctx\":\"thread1\",\"msg\":\"Trying to start Windows service\",\"attr\":{\"serviceName\":\"MongoDB\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.123+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":15020,\"port\":27017,\"dbPath\":\"C:/data/db\",\"architecture\":\"64-bit\",\"host\":\"LAPTOP-RJ5HAO5L\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.123+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23398, \"ctx\":\"initandlisten\",\"msg\":\"Target operating system minimum version\",\"attr\":{\"targetMinOS\":\"Windows 7/Windows Server 2008 R2\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.123+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"6.0.2\",\"gitVersion\":\"94fb7dfc8b974f1f5343e7ea394d0d9deedba50e\",\"modules\":[],\"allocator\":\"tcmalloc\",\"environment\":{\"distmod\":\"windows\",\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.123+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Microsoft Windows 10\",\"version\":\"10.0 (build 22621)\"}}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.123+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{\"config\":\"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\6.0\\\\bin\\\\mongod.cfg\",\"net\":{\"bindIp\":\"127.0.0.1\"},\"service\":true,\"storage\":{\"dbPath\":\"C:\\\\data\\\\db\"},\"systemLog\":{\"destination\":\"file\",\"logAppend\":true,\"path\":\"C:\\\\Program Files\\\\MongoDB\\\\Server\\\\6.0\\\\log\\\\mongod.log\"}}}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.124+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22270, \"ctx\":\"initandlisten\",\"msg\":\"Storage engine to use detected by data files\",\"attr\":{\"dbpath\":\"C:/data/db\",\"storageEngine\":\"wiredTiger\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.124+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22315, \"ctx\":\"initandlisten\",\"msg\":\"Opening WiredTiger\",\"attr\":{\"config\":\"create,cache_size=7294M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.369+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4795906, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger opened\",\"attr\":{\"durationMillis\":245}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.369+02:00\"},\"s\":\"I\", \"c\":\"RECOVERY\", \"id\":23987, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger recoveryTimestamp\",\"attr\":{\"recoveryTimestamp\":{\"$timestamp\":{\"t\":0,\"i\":0}}}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.372+02:00\"},\"s\":\"W\", \"c\":\"CONTROL\", \"id\":22120, \"ctx\":\"initandlisten\",\"msg\":\"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted\",\"tags\":[\"startupWarnings\"]}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.374+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915702, \"ctx\":\"initandlisten\",\"msg\":\"Updated wire specification\",\"attr\":{\"oldSpec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"outgoing\":{\"minWireVersion\":6,\"maxWireVersion\":17},\"isInternalClient\":true},\"newSpec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"incomingInternalClient\":{\"minWireVersion\":17,\"maxWireVersion\":17},\"outgoing\":{\"minWireVersion\":17,\"maxWireVersion\":17},\"isInternalClient\":true}}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.375+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5853300, \"ctx\":\"initandlisten\",\"msg\":\"current featureCompatibilityVersion value\",\"attr\":{\"featureCompatibilityVersion\":\"6.0\",\"context\":\"startup\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.375+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":5071100, \"ctx\":\"initandlisten\",\"msg\":\"Clearing temp directory\"}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.375+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20536, \"ctx\":\"initandlisten\",\"msg\":\"Flow Control is enabled on this deployment\"}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.639+02:00\"},\"s\":\"I\", \"c\":\"FTDC\", \"id\":20625, \"ctx\":\"initandlisten\",\"msg\":\"Initializing full-time diagnostic data capture\",\"attr\":{\"dataDirectory\":\"C:/data/db/diagnostic.data\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.642+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":6015317, \"ctx\":\"initandlisten\",\"msg\":\"Setting new configuration state\",\"attr\":{\"newState\":\"ConfigReplicationDisabled\",\"oldState\":\"ConfigPreStart\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.642+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22262, \"ctx\":\"initandlisten\",\"msg\":\"Timestamp monitor starting\"}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.644+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":23015, \"ctx\":\"listener\",\"msg\":\"Listening on\",\"attr\":{\"address\":\"127.0.0.1\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.644+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":23016, \"ctx\":\"listener\",\"msg\":\"Waiting for connections\",\"attr\":{\"port\":27017,\"ssl\":\"off\"}}\n{\"t\":{\"$date\":\"2022-10-27T15:44:47.644+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20555, \"ctx\":\"initandlisten\",\"msg\":\"Service running\"}\n\n"}, {"role": "assistant", "content": "Text:Any success?\nIt says waiting for connections but SSL:off\nDid you try 0.0.0.0 inplace of localhost in your connect string.It is suggested as one of the fix in a forum thread\nCode:"}, {"role": "user", "content": "Text:Yes I tried it all. I think I\u2019ll give up, thanks for your help anyways\nCode:"}, {"role": "assistant", "content": "Text:Please share a screenshot that shows exactly how you start your application.If mongosh can connect, your application should connect.Are you using docker or some other container to start the application?I do not know exactly which commands are available inside WSL terminal, but the output of the following (if available)\nCode:ss -tlnp\nps -aef | grep [m]ongo\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongod.service: Failed with result 'exit-code' and tags: []"}, {"role": "user", "content": "Text:i have been using sudo sytemctl start mongod for while without having issues but lately whenever i run the same command to start mongodb and try to check the status i keep getting this failed message.how do i fix this?\nCode:sudo sytemctl start mongodmongod.service - MongoDB Database Server\n Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)\n Active: failed (Result: exit-code) since Wed 2022-10-19 20:11:41 WAT; 47min ago\n Docs: https://docs.mongodb.org/manual\n Process: 5770 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=48)\n Main PID: 5770 (code=exited, status=48)\n\nOct 19 20:11:40 systemd[1]: Started MongoDB Database Server.\nOct 19 20:11:41 systemd[1]: mongod.service: Main process exited, code=exited, status=48/n/a\nOct 19 20:11:41 systemd[1]: mongod.service: Failed with result 'exit-code'.\n"}, {"role": "assistant", "content": "Text:Please share the content of the log file and configuration file.Also share the output of:If I remember correctly status=48 means you have another process listening at the same address/port.\nCode:ps -aef | grep [m]ongo\nss -tlnp\n"}, {"role": "user", "content": "Text:here\u2019s my config file content Steeveps -aef | grep [m]ongo outputss -tlnpplease, how do i go about handling the status=48 ?\nthanks.\nCode:{\"userId\":\"626bc8fbd5796d38ef89118f\",\"telemetryAnonymousId\":\"626bc8fbd5796d38ef89118f\",\"enableTelemetry\":true,\"disableGreetingMessage\":true}\nps -aef | grep [m]ongo outputmongodb 2122 1 0 11:12 ? 00:00:07 /usr/bin/mongod --config /etc/mongodb.conf\nss -tlnpState Recv-Q Send-Q Local Address:Port Peer Address:Port Process \nLISTEN 0 70 127.0.0.1:33060 0.0.0.0:* \nLISTEN 0 4096 127.0.0.1:27017 0.0.0.0:* \nLISTEN 0 151 127.0.0.1:3306 0.0.0.0:* \nLISTEN 0 511 0.0.0.0:80 0.0.0.0:* \nLISTEN 0 32 192.168.122.1:53 0.0.0.0:* \nLISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:* \nLISTEN 0 5 127.0.0.1:631 0.0.0.0:* \nLISTEN 0 244 127.0.0.1:5432 0.0.0.0:* \nLISTEN 0 244 127.0.0.1:5433 0.0.0.0:* \nLISTEN 0 244 127.0.0.1:5434 0.0.0.0:* \nLISTEN 0 244 127.0.0.1:5435 0.0.0.0:* \nLISTEN 0 50 [::ffff:127.0.0.1]:9614 *:* users:((\"java\",pid=2715,fd=17)) \nLISTEN 0 511 [::]:80 [::]:* \nLISTEN 0 5 [::1]:631 [::]:* \n"}, {"role": "user", "content": "Text:I have been able to fixed the issue.\n@steevej\nThe mongod service process tries to run on the same port and this was as a result of previously running mongod service with root privileged on ubuntu.\ni had to kill the process on the port mongod service is listening to without worrying if the service has been started by another user.\nCode:sudo fuser -k 27017/tcp\n"}, {"role": "assistant", "content": "Text:I am sorry but I did missed the post you made 14 days ago.Thanks for sharing the solution.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Connect ECONNREFUSED 127.0.0.1:27017 and tags: ['node-js', 'server']"}, {"role": "user", "content": "Text:I encounter this error message when I try to establish a connection, and my operating system is Windows. I have already tried reinstalling multiple times, but I can\u2019t resolve it\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Mongoose .populate() is not working with node.js app and tags: ['aggregation', 'node-js', 'data-modeling', 'mongoose-odm']"}, {"role": "user", "content": "Text:First post here, so hello to everyone!I\u2019m having trouble with mongoose populate because it\u2019s apparently doing nothing. I\u2019m going straight to the code.Here are my models:SpaceDayAnd the part of the controller where I have the getSpace route (/api/spaces/:id):And this is the result I get:I tried many things, but all the results were the same.Let me know if you need any other part of the code.Thank you all I expect the result to look something like this\nCode:const spaceSchema = Schema(\n\t{\n\t\tuser: {\n\t\t\ttype: Schema.Types.ObjectId,\n\t\t\trequired: true,\n\t\t\tref: \"User\",\n\t\t},\n\t\tname: {\n\t\t\ttype: String,\n\t\t\trequired: true,\n\t\t},\n\t\tdays: [{ type: Schema.Types.ObjectId, refPath: \"Day\" }],\n\t},\n\t{\n\t\tversionKey: false,\n\t timestamps: true \n },\n);\n\nconst Space = mongoose.model(\"Space\", spaceSchema);\n\nmodule.exports = Space;\n\nconst daySchema = Schema(\n\t{\n\t\tspace: { type: Schema.Types.ObjectId, refPath: \"Space\" },\n\t\tdate: {\n\t\t\ttype: String,\n\t\t\trequired: true,\n\t\t},\n\t\twater: {\n\t\t\ttype: Boolean,\n\t\t},\n\t\tfertilizer: {\n\t\t\ttype: Boolean,\n\t\t},\n\t\ttransplant: {\n\t\t\ttype: Boolean,\n\t\t},\n\t\tcomment: {\n\t\t\ttype: String,\n\t\t},\n\t},\n\t{\n\t\tversionKey: false,\n\t timestamps: true \n },\n);\n\nconst Day = mongoose.model(\"Day\", daySchema);\n\nmodule.exports = Day;\nconst getSpace = asyncHandler(async (req, res) => {\n\tconst space = await Space.findById(req.params.id).populate(\"days\");\n\tres.status(200).json(space);\n});\n\n{\n \"_id\": \"63580115978dbf8f2f5a7a50\",\n \"user\": \"63501ab84613855834daa4ef\",\n \"name\": \"spaceName\",\n \"days\": []\n}\n \"space\": {\n \"_id\": \"63580115978dbf8f2f5a7a50\",\n \"user\": \"63501ab84613855834daa4ef\",\n \"name\": \"spaceName\",\n \"days\": [\n {\n \"_id\": \"63581af565aed8cad3210046\",\n \"space\": \"63580115978dbf8f2f5a7a50\",\n \"date\": \"29/10/2022\",\n \"water\": true,\n \"fertilizer\": true,\n \"transplant\": false,\n \"comment\": \"This is a comment.\",\n \"createdAt\": ...,\n \"updatedAt\": ...\n },\n {\n \"_id\": \"63581af565aed8cad3210046\",\n \"space\": \"63580115978dbf8f2f5a7a50\",\n \"date\": \"29/10/2022\",\n \"water\": false,\n \"fertilizer\": false,\n \"transplant\": true,\n \"comment\": \"This is a comment.\",\n \"createdAt\": ...,\n \"updatedAt\": ...\n }\n ]\n }\n\n"}, {"role": "assistant", "content": "Text:refPath doesn\u2019t mean, what you might think it does. What you need here is a simple ref.\nSo, just change refPath to ref in your schemas and your example should be working as you expect.But, there is a second thing. You have redundant references: days refer to spaces and spaces to days. Generally you don\u2019t need to refer to each other in both ways (unless in your specific use case you do). For many-to-one or many-to-many relations there are Populate Virtuals. You can read up on it in the Mongoose documentation.So I would get rid of the days field in the Space schema, and replace it with a populate virtual:\nCode:refPathrefrefPathrefdaysconst spaceSchema = Schema(\n\t{\n\t\tuser: {\n\t\t\ttype: Schema.Types.ObjectId,\n\t\t\trequired: true,\n\t\t\tref: \"User\",\n\t\t},\n\t\tname: {\n\t\t\ttype: String,\n\t\t\trequired: true,\n\t\t},\n\t},\n\t{\n\t\tversionKey: false,\n\t\ttimestamps: true,\n\t},\n);\n\nspaceSchema.virtual('days', {\n\tref: 'Day',\n\tlocalField: '_id',\n\tforeignField: 'space',\n});\n\nconst Space = mongoose.model(\"Space\", spaceSchema);\n\nmodule.exports = Space;\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How to count documents in pymongo and tags: ['aggregation', 'python']"}, {"role": "user", "content": "Text:Hey People,\nI know this is one of the most basic topics but I cant figure out where im going wrong, trying . count() and .count_documents() and getting the following error:Cursor' object has no attribute 'count_documents\nCursor' object has no attribute 'count.the code im using is:im feeling quite dumb here\u2026\nCode: count().count_documents()Cursor' object has no attribute 'count_documentsCursor' object has no attribute 'counturi = \"XXXXXXXXXX\"\nclient = MongoClient(URI); # creating an instance of the client\n\nprint(client.sample_training.zips.find(\n {\n \"pop\" : {\"$lt\" : 1000}\n }\n\n ).count_documents())\n"}, {"role": "user", "content": "Text:I figured out the answer, in case anyone else is interested:\nCode:uri = \"XXXXXXXXXX\"\nclient = MongoClient(URI);\n\nclient.sample_training.zips.count_documents(\n {\n \"pop\" : {\"$lt\" : 1000}\n }\n)\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Read change streams with multiple threads and tags: ['change-streams']"}, {"role": "user", "content": "Text:Hi everyone,I have a question. Is there anyway to read change streams with multiple threads?Ex: we have 3 messages in change streams\nmessages = [A, B, C]\nand my client has 2 threads. I want these 2 threads can receive messages in parallel. Ex:\nthread 1: receive [A, C]\nthread 2: receive [B]Assume that I don\u2019t care about the ordering of messages, i.e: timestamp. I just want to read as fast as possible.\nCode:messages = [A, B, C]"}, {"role": "assistant", "content": "Text:You can have multiple thread receiving different change stream message if the query used to set up the stream is different.If the query is the same then all receive the message.If you want to load balance you can easily do it internally or with any message queue framework.\nCode:"}, {"role": "user", "content": "Text:Basically, I want multiple threads can receive different messages in parallel from a change streams (ex: change streams from a specific collection in MongoDB).\nIt seems that there\u2019s no way to do that.My problem is that I have 10.000 updates/sec in MongoDB. In my client program, I want to receive these 10.000 messages via change streams (FULL_DOCUMENT, each document is around 100KB) with Java API of change streams. I want to speed this process up by using multiple threads (Assume that I don\u2019t care about the ordering of messages).\nCode:"}, {"role": "assistant", "content": "Text:(ex: change streams from a specific collection in MongoDB).\nIt seems that there\u2019s no way to do that.please revise the documentation because you can do the above\nCode:"}, {"role": "user", "content": "Text:Thank Steeve for your reply.Could you please give me the link to that documentation? I\u2019ve got stuck for a few days for this problem and couldn\u2019t find any helpful link.I have 10k changes/sec in MongoDB. In my client program, I want to receive these 10k changes (fullDocument, each doc is around 100KB, so it\u2019s around 1GB data/sec) with Java API of change streams. I want to speed this process up by using multiple threads (assume that I don\u2019t care about the ordering of messages). Below is a normal way to work with change streams. How to speed it up?\nCode: MongoCollection collection = db.getCollection(\"my_collection\");\n ChangeStreamIterable iterable = collection.watch();\n\n iterable.forEach(new Consumer>() {\n @Override\n public void accept(ChangeStreamDocument doc) {\n // do something with doc\n }\n });"}, {"role": "assistant", "content": "Text:Documentation can be found with google search.https://www.google.com/search?q=mongodb+change+streamsYou write(ex: change streams from a specific collection in MongoDB).\nIt seems that there\u2019s no way to do that.but you share the codewhich does exactlychange streams from a specific collection\nCode:MongoCollection collection = db.getCollection(\"my_collection\");\nChangeStreamIterable iterable = collection.watch();\n"}, {"role": "user", "content": "Text:Oh Steeve, maybe my explanation is pretty bad. What I want is \u201cmultiple threads can receive different messages in parallel from a change streams\u201d. You can see the problem (10k changes/sec) that I described above.The key problem is I want \u201cmutiple threads\u201d and \u201cparallel\u201d.I mean I want to receive messages in parallel from change stream of something like: database, a single collection, multiple collections. So I wrote \u201cex: change streams from a specific collection\u201d.Of course, I know how to receive message in single thread as same as the code that I shared. It\u2019s easy.\nCode:"}, {"role": "assistant", "content": "Text:As I originally wrote:If the query is the same then all receive the message.If you want to load balance you can easily do it internally or with any message queue framework.\nCode:"}, {"role": "user", "content": "Text:If the query is the same then all receive the message.yeah, so there\u2019s no way to parallel the following codeIf we want to parallelize, we have to as follows but it\u2019s very trickyI don\u2019t understand this ideaIf you want to load balance you can easily do it internally or with any message queue framework.The main problem is how to parallelize if the query is the same? How to use message queue here? My pain point is that if the query is the same, we won\u2019t be able to properly parallelize it without tricky. The bottleneck is if it\u2019s the same query, the speed of reading from change stream is pretty bad.\nCode: ChangeStreamIterable iterable = collection.watch();\n iterable.forEach(new Consumer>() {\n @Override\n public void accept(ChangeStreamDocument doc) {\n // do something with doc\n }\n });\nChangeStreamIterable iterable1 = collection.watch(query1); // query1 can be id in a specific range\nChangeStreamIterable iterable2 = collection.watch(query2); \n"}, {"role": "assistant", "content": "Text:If we want to parallelize, we have to as follows but it\u2019s very trickyHow is that tricky? The queries are different, they will receive different change stream events.Like you wrote:The main problem is how to parallelize if the query is the sameAs forHow to use message queue here?See how to use message queues - Google Search.If reading becomes the bottleneck you will have to distribute the load among different machines rather than multiple threads.\nCode:ChangeStreamThread thread_query_1 = new ChangeStreamThread( query1 ).start() ;\nChangeStreamThread thread_query_2 = new ChangeStreamThread( query2 ).start() ;\nclass ChangeStreamThread extends Thread\n{\n Document m_Query ;\n\n ChangeStreamThread( Document query )\n {\n m_Query = query ;\n }\n public void run()\n {\n // What ever code you have to process the events matching m_Query from the stream\n }\n}\n"}, {"role": "user", "content": "Text:Thank Steevej for your response.How is that tricky? The queries are different, they will receive different change stream events.The problem is it\u2019s just a collection. Normally, we use a change stream for this collection as follows:The tricky is I split the change stream to multiple change streams by queries as I wrote (note that I just have 1 collection). So which queries should be chose?Of course, I can use 2 threads here with this 2 queries. The trick is I have to think about some queries to split a change stream to multiple change streams.So I want to use the same query (no query) as follows.How can I parallelize/use multi threads here?See how to use message queues - Google Search.My question is HOW to use it in MY USE CASE.If reading becomes the bottleneck you will have to distribute the load among different machines rather than multiple threads.There\u2019re 2 things here:My client programMongoDBWhich thing did you suggest to scale? client or mongo or both? Note that it\u2019s just a single collection.\nMaybe you suggests to distribute this collection to multiple mongo nodes (machines) and then will use different clients (on different machines), right?I haven\u2019t had experiences about mongo. Sorry if there\u2019re some stupid questions.\nCode:ChangeStreamIterable iterable = collection.watch();\nChangeStreamIterable iterable1 = collection.watch(query1); // query1 can be id in a specific range\nChangeStreamIterable iterable2 = collection.watch(query2); \nChangeStreamIterable iterable = collection.watch();\n"}, {"role": "assistant", "content": "Text:I\u2019m also experimenting with consuming change streams from multiple threads, and I guess it could be possible to do like this:\nCode: MongoCollection events = test.getCollection(\"some-model\", SomeModel.class);\n ChangeStreamIterable watch = events.watch();\n ExecutorService executorService = Executors.newSingleThreadExecutor(); // adjust the thread pool as preferred\n executorService.execute(() -> {\n watch.forEach(csd -> {\n System.out.printnl(\"changeStreamDocument: \" + csd); // this logic is called in each thread\n });\n });\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Intermittent MongoServerSelectionError when connecting from NodeJS using Google Cloud Run + MongoDB Atlas and tags: ['node-js', 'connecting']"}, {"role": "user", "content": "Text:Hey folks,Hi, I\u2019m having problems with connecting to MongoDB Atlas from a Google Cloud Run instance. I\u2019m intermittently (a few times per day) getting a MongoServerSelectionError when my server is initializing and trying to connect. This is my current setup:I\u2019m not seeing any alerts in MongoDB atlas. Please note that this is an intermittent issue. Sometimes it connects sometimes it doesn\u2019t. Because my app currently has very low traffic there is never more than one instance running so the 30-second timeout + time to restart of the container makes this problem critical.Here\u2019s the stack trace:MongoServerSelectionError: connection timed out at Timeout._onTimeout (/usr/src/app/node_modules/mongodb/lib/core/sdam/topology.js:438:30) at listOnTimeout (internal/timers.js:549:17) at processTimers (internal/timers.js:492:7) {\nreason: TopologyDescription {\ntype: \u2018ReplicaSetNoPrimary\u2019,\nsetName: null,\nmaxSetVersion: null,\nmaxElectionId: null,\nservers: Map {\n\u2018xxx-00-00-0qvnm.gcp.mongodb.net:27017\u2019 => [ServerDescription],\n\u2018xxx-00-01-0qvnm.gcp.mongodb.net:27017\u2019 => [ServerDescription],\n\u2018xxx-00-02-0qvnm.gcp.mongodb.net:27017\u2019 => [ServerDescription]\n},\nstale: false,\ncompatible: true,\ncompatibilityError: null,\nlogicalSessionTimeoutMinutes: null,\nheartbeatFrequencyMS: 10000,\nlocalThresholdMS: 15,\ncommonWireVersion: null\n}Can anybody assist with troubleshooting this?Regards,\nStefan\nCode:"}, {"role": "user", "content": "Text:Sorry I\u2019m on MongoDB version 4.2 not 4.4\nCode:"}, {"role": "assistant", "content": "Text:Has this issue been resolved for you? I\u2019m having the same issue, of intermittent connectivity due to a timeout, but mine is happening from a DigitalOcean droplet. I\u2019ve tried almost everything, except use Mongoose.For my setup:\nCode:Mongoose"}, {"role": "assistant", "content": "Text:I resolved it by setting useUnifiedTopology: false, works great now.\nCode:useUnifiedTopology: false"}, {"role": "assistant", "content": "Text:I had a similar issue, however setting the useUnifiedTopology: false did not help me in my case.\nIs there any other fixes to solve this error?\nCode:useUnifiedTopology: false"}, {"role": "assistant", "content": "Text:Hi, I am new to MongoDB Atlas too. A few days ago, I had connection problem using Python. I have managed to find a solution for that.Just now, using MongoDB Atlas NodeJs tutorial, using the same Atlas connection string in my Python stuff. I had the below timeout error.It turned out, my Public IP address has changed because I reset my Windows 10 internet connection. I added the new Public IP to Atlast IP whitelist and it works.This is my case. I am new to this, I hope this might help someone\u2026MongoServerSelectionError: connection to 13.55.193.163:27017 closed\nat Timeout._onTimeout (D:\\Codes\\nodejs\\mongodb\\node_modules\\mongodb\\lib\\sdam\\topology.js:312:38)\nat listOnTimeout (node:internal/timers:557:17)\nat processTimers (node:internal/timers:500:7) {\nreason: TopologyDescription {\ntype: \u2018ReplicaSetNoPrimary\u2019,\nservers: Map(3) {\n\u2018cluster0-shard-00-00 . 71o6u . mongodb . net : 27017\u2019 => [ServerDescription],\n\u2018cluster0-shard-00-01.71o6u.mongodb.net 27017\u2019 => [ServerDescription],\n\u2018cluster0-shard-00-02.71o6u.mongodb.net:27017\u2019 => [ServerDescription]\n},\nstale: false,\ncompatible: true,\nheartbeatFrequencyMS: 10000,\nlocalThresholdMS: 15,\nsetName: \u2018atlas-vx7zhd-shard-0\u2019,\nlogicalSessionTimeoutMinutes: undefined\n}\n}\nCode:"}, {"role": "assistant", "content": "Text:This article helped me with this issue. Fixing MongoServerSelectionError while connecting MongoDB with node.js | by Barak Saidoff | Medium\nCode:"}, {"role": "assistant", "content": "Text:@Stefan_Li Did you fix this? I have the same problem and cannot find a way to resolve it\nCode:"}, {"role": "assistant", "content": "Text:Same - I also keep getting the error intermittently when using Cloud Run with Atlas.\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Store and serve pdf documents and tags: []"}, {"role": "user", "content": "Text:Good Morning. I need to store and save pdf and doc documents. Which is the best option? Thank you\nCode:"}, {"role": "assistant", "content": "Text:Good Morning @francisco_jose, welcome to MongoDB forum.In MongoDB, you use GridFS for storing files larger than 16 MB.If the files (i.e., each of them) to be stored are within the 16 MB limit of BSON document size, then you can store the files within a collection\u2019s document as a field of type Binary Data (binData).\nCode:binData"}, {"role": "user", "content": "Text:Thanks for quick reply. Still separate the data into two custer? One for data related to pdf and the other for pdf? Best regards\nCode:"}, {"role": "assistant", "content": "Text:What are you considering - GridFS or within a document? What is the maximum size of the PDF documents?\nCode:"}, {"role": "assistant", "content": "Text:In case of GridFS, the file and its information is stored in two collections (the files and chunks collections). The files stores the file\u2019s metadata (information about the file like, id, length / size, filename, content type, etc.) and the chunks stores the actual file data.In case of a document as a file store, you can have additional fields specifying the file name, description etc., that is within the same document of the collection.\nCode:fileschunksfileschunks"}, {"role": "assistant", "content": "Text:I tried importing pdf files to gridfs. As everything is stored in BSON, is it possible to export the pdf file from mongodb which I imported ?\nCode:"}, {"role": "assistant", "content": "Text:Take a look at https://www.mongodb.com/docs/database-tools/mongofiles/#mongodb-binary-bin.mongofiles\nCode:"}, {"role": "assistant", "content": "Text:Thank you. mongofiles command works\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Extremely slow GraphQL performance even with very simple query and schema and tags: ['performance']"}, {"role": "user", "content": "Text:I am trying to switch over from REST to GraphQL, and am experiencing horribly slow responses for queries. As in 5000-7000+ ms for a super simple, small request. I\u2019ve spent days on this, tried everything, and am about to give up. Any help would be greatly appreciated.I have greatly reduced the schema from the huge one auto-generated to a tiny one for testing (no difference), implemented filters (no difference), simplified the query to only return a few, have indexed the main field (helped a tiny bit), and have not resolvers or anything special at all.I am on the M10 tier.The schema:The query:A sample log entry:I have an index on startDate as well. The result set is only 6k. Please help! Surely I am missing something, or there is some explanation, as this is completely unusable.Best,\nGreg\nCode:{\n \"title\": \"mlbgame\",\n \"properties\": {\n \"_id\": {\n \"bsonType\": \"string\"\n },\n \"_simulation\": {\n \"bsonType\": \"bool\"\n },\n \"date\": {\n \"bsonType\": \"string\"\n },\n \"endDate\": {\n \"bsonType\": \"date\"\n },\n \"gameInfo\": {\n \"bsonType\": \"string\"\n },\n \"gameStatus\": {\n \"bsonType\": \"string\"\n },\n \"id\": {\n \"bsonType\": \"string\"\n },\n \"minutesRemaining\": {\n \"bsonType\": \"int\"\n },\n \"percentComplete\": {\n \"bsonType\": \"double\"\n },\n \"sport\": {\n \"bsonType\": \"string\"\n },\n \"startDate\": {\n \"bsonType\": \"date\"\n },\n \"status\": {\n \"bsonType\": \"string\"\n }\n }\n}\nquery GamesForCalendar($dateFrom: DateTime!, $dateTo: DateTime!) {\n mlbgames(query: {startDate_gte: $dateFrom, startDate_lte: $dateTo}) {\n id\n status\n sport\n date\n startDate\n endDate\n gameInfo\n gameStatus\n minutesRemaining\n percentComplete\n _simulation\n }\n }\nFunction Call Location:\nUS-OR\nGraphQL Query:\nquery GamesForCalendar($dateFrom: DateTime!, $dateTo: DateTime!) { mlbgames(query: {startDate_gte: $dateFrom, startDate_lte: $dateTo}) { id status sport date startDate endDate gameInfo gameStatus minutesRemaining percentComplete _simulation __typename } }\nCompute Used:\n18736722090 bytes\u2022ms\nRemote IP Address:\n136.32.230.69\nRule Performance Metrics:\n{\n \"dfsdb.mlbgames\": {\n \"roles\": {\n \"default\": {\n \"matching_documents\": 19,\n \"evaluated_fields\": 0,\n \"discarded_fields\": 0\n }\n },\n \"no_matching_role\": 0\n }\n}\n"}, {"role": "user", "content": "Text:@Pavel_Duchovny Hi, did I post this incorrectly or in the wrong place? It would have sure been nige to give GraphGL with my application to see if it would have been best, but never could get past this issue. And no-one responded. I thought I did a decent job of describing the issue, so hoped it would have been an easy fix.Thanks.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Gregory_Fay sorry that we missed your original post! Do you happen to know the realm app deployment model and region that your atlas cluster is deployed in? Some things that may cause slower queries with GraphQL includeLet me know if one or more oof these things seems like it may be the issue here.\nCode:"}, {"role": "user", "content": "Text:Hi @Sumedha_Mehta1Thank you for the reply. I missed it, and it got buried. I had to go another direction for now but will try to recreate what I had and see if any of these suggestions solve the problem. I was so excited about GraphQL until I couldn\u2019t get the basics to work!Thanks,\nGreg\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Best way to batch queries and tags: ['node-js']"}, {"role": "user", "content": "Text:What is the best way to batch multiple queries into a single request? My goal is to avoid incurring the multiplied latency from serial requests, but also avoid opening too many connections for parallel requests. Ideally I would be able to say db.bulkRead([query1, query2, query3]) and get back a (potentially paginated) list of results.I\u2019m also curious if the driver automatically does something like this (i.e. if I send two requests with maxPoolSize=1, will the driver wait for the first request to fully complete before issuing the second request? Or could it send both across a single connection, and just get the response streamed in after?). I would prefer a system where I could choose what to batch to ensure large queries aren\u2019t mixed into batches of cheap queries.From my research so far, it seems like this exists but only with bulkWrites, and I\u2019m not sure why it wouldn\u2019t exist for bulkRead as well.\nCode:"}, {"role": "assistant", "content": "Text:Hi @Alex_Coleman ,Making the poolsize to one will not increase on parallel execution of queries. On the other hand it will harm it.The best way to batch data fetch in MongoDB is to store it embedded in documents. Meaning that if you need to always fetch related data together store it together in a single document. If not possible store it in a chain of documents in a single collection with a predict that you can identify for example an id for a batch grab indexed.Other less recommended technics are using a unionWith aggregation or a $facet search with multiple facets as batches or $lookup to access different collections in a single query.I recommend reading some of our blogs on data designHave you ever wondered, \"How do I model a MongoDB database schema for my application?\" This post answers all your questions!A summary of all the patterns we've looked at in this seriesThanks\nPavel\nCode:"}, {"role": "user", "content": "Text:Hi Pavel,Thanks for the answer. I understand that a higher poolsize is best for parallel execution of queries, but I was just curious the exact effect of using a single connection. In particular, if execution was serial or just the writing of query/response to the DB was serial (which would be less of an issue since it doesn\u2019t incur latency cost twice).I agree its best to store related data together in similar documents and such. However, across a large application issuing many queries it would be nice if there was a way to batch unrelated queries. Facet seems like exactly the answer I\u2019m looking for, but it doesn\u2019t support indexes on the contents. Do you know if there\u2019s any way to do something similar? Basically I just want a {$or: [$query1, $query2]}, but with the results of each query labeled. Thanks!\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Cannot Start mongodb-community and tags: ['server']"}, {"role": "user", "content": "Text:Hello,I tried every solution here but I still get the same error when I try to start mongodb-community edition through brew services start mongodb-community\nor\nbrew services restart mongodb-community\nor\nbrew services start mongodb-community@6.0\nEkran Resmi 2022-10-04 18.37.301202\u00d7182 37.2 KB\nI deleted the 27017.sock file and tried these things again. At some point I always get the same error when I\nbrew services listName Status User File\nmongodb-community error 3584 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plistAnd this error while trying to restart.\nError: Failure while executing; /bin/launchctl bootstrap gui/501 /Users/macbook/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist exited with 5.When I tried to start it \u201csudo\u201d, I get the error below;\nError: Failure while executing; /bin/launchctl bootstrap system /Library/LaunchDaemons/homebrew.mxcl.mongodb-community.plist exited with 37.Can anyone help me on this? This really got my days and I\u2019m frustrated.\nCode:brew services start mongodb-communitybrew services restart mongodb-communitybrew services start mongodb-community@6.0brew services listName Status User Filemongodb-community error 3584 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist/bin/launchctl bootstrap gui/501 /Users/macbook/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist/bin/launchctl bootstrap system /Library/LaunchDaemons/homebrew.mxcl.mongodb-community.plist"}, {"role": "assistant", "content": "Text:Have you looked at the MongoDB log file to see what\u2019s being written to it? That should have the error that\u2019s happening. If you can post the log showing the most recent attempt to start the process we can use that to help you out.Also note that you shouldn\u2019t ever run the MongoDB process as the root user (running with sudo) as this sets permission on files/directories that cause issues when you try to run as your normal user. Running as root can also lead to escalation of privileges and allow for bad things to happen.\nCode:rootsudoroot"}, {"role": "user", "content": "Text:Is it something like this? I used\ntail $(brew --prefix)/var/log/mongodb/mongo.logto get this.\nCode:{\"t\":{\"$date\":\"2022-10-04T18:29:00.238+03:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22270, \"ctx\":\"initandlisten\",\"msg\":\"Storage engine to use detected by data files\",\"attr\":{\"dbpath\":\"/Users/macbook/Desktop/mongodatabasepathtest\",\"storageEngine\":\"wiredTiger\"}}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.238+03:00\"},\"s\":\"W\", \"c\":\"STORAGE\", \"id\":22302, \"ctx\":\"initandlisten\",\"msg\":\"Recovering data from the last clean checkpoint.\"}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.238+03:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22315, \"ctx\":\"initandlisten\",\"msg\":\"Opening WiredTiger\",\"attr\":{\"config\":\"create,cache_size=3584M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],\"}}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.948+03:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":1,\"message\":\"[1664897340:946133][2690:0x11404f600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /Users/macbook/Desktop/mongodatabasepathtest/WiredTiger.turtle: handle-open: open: Operation not permitted\"}}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.951+03:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":1,\"message\":\"[1664897340:951390][2690:0x11404f600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /Users/macbook/Desktop/mongodatabasepathtest/WiredTiger.turtle: handle-open: open: Operation not permitted\"}}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.952+03:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":1,\"message\":\"[1664897340:952344][2690:0x11404f600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /Users/macbook/Desktop/mongodatabasepathtest/WiredTiger.turtle: handle-open: open: Operation not permitted\"}}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.952+03:00\"},\"s\":\"W\", \"c\":\"STORAGE\", \"id\":22347, \"ctx\":\"initandlisten\",\"msg\":\"Failed to start up WiredTiger under any compatibility version. This may be due to an unsupported upgrade or downgrade.\"}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.952+03:00\"},\"s\":\"F\", \"c\":\"STORAGE\", \"id\":28595, \"ctx\":\"initandlisten\",\"msg\":\"Terminating.\",\"attr\":{\"reason\":\"1: Operation not permitted\"}}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.952+03:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23091, \"ctx\":\"initandlisten\",\"msg\":\"Fatal assertion\",\"attr\":{\"msgid\":28595,\"file\":\"src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp\",\"line\":702}}\n{\"t\":{\"$date\":\"2022-10-04T18:29:00.952+03:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23092, \"ctx\":\"initandlisten\",\"msg\":\"\\n\\n***aborting after fassert() failure\\n\\n\"}\ntail $(brew --prefix)/var/log/mongodb/mongo.log"}, {"role": "assistant", "content": "Text:The following sticks out:\"Failed to start up WiredTiger under any compatibility version. This may be due to an unsupported upgrade or downgrade.\"It seems like there are data files in the dbPath that are not compatible with the version of MongoDB that you are running. You can either delete all the files in this path if the data is not needed. If you need/want to keep this data, then you can move them off in a new location and then try to figure out what version of MongoDB those files were created with and start that version of the mongod process at a later time. Once you have a clean dbPath directory, try running your brew services restart ... command again and see if you can get the process started.\nCode:\"Failed to start up WiredTiger under any compatibility version. This may be due to an unsupported upgrade or downgrade.\"dbPathmongoddbPathbrew services restart ..."}, {"role": "user", "content": "Text:Hello,I have changed my config file. And the dbPath part is empty now. This is how my config file looks right now.However, this time I get another error when I try to restart my mongo community. This is the error right now.After this error I checked this linkAnd I changed dbPath line to:dbPath: /usr/local/var/mongodbHowever, I get another error which has the sam error number like the first one (3584), like the one below:When I try to open the file in the error, I get an error like this.Because I have deleted that file formerly.This is the latest log.Can you guys help me please? I\u2019ve been struggling for days. Thank you.\nCode:systemLog:\n destination: file\n path: /usr/local/var/log/mongodb/mongo.log\n logAppend: true\nstorage:\n dbPath:\nnet:\n bindIp: 127.0.0.1, ::1\n ipv6: true\nName Status User File\nmongodb-community error 25600 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist\ndbPath: /usr/local/var/mongodbName Status User File\nmongodb-community error 3584 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist\nThe file /Users/macbook/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist does not exist.\nmacbook@SamsMacbook ~ % tail $(brew --prefix)/var/log/mongodb/mongo.log \n{\"t\":{\"$date\":\"2022-10-07T19:11:33.261+03:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"namespace\":\"config.tenantMigrationRecipients\"}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.261+03:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"ShardSplitDonorService\",\"namespace\":\"config.tenantSplitDonors\"}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.261+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"main\",\"msg\":\"Multi threading initialized\"}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.261+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":31154,\"port\":27017,\"dbPath\":\"\",\"architecture\":\"64-bit\",\"host\":\"SamsMacbook.local\"}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.261+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"6.0.1\",\"gitVersion\":\"32f0f9c88dc44a2c8073a5bd47cf779d4bfdee6b\",\"modules\":[],\"allocator\":\"system\",\"environment\":{\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.261+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Mac OS X\",\"version\":\"21.3.0\"}}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.261+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{\"config\":\"/usr/local/etc/mongod.conf\",\"net\":{\"bindIp\":\"127.0.0.1, ::1\",\"ipv6\":true},\"storage\":{\"dbPath\":true},\"systemLog\":{\"destination\":\"file\",\"logAppend\":true,\"path\":\"/usr/local/var/log/mongodb/mongo.log\"}}}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.262+03:00\"},\"s\":\"E\", \"c\":\"NETWORK\", \"id\":23024, \"ctx\":\"initandlisten\",\"msg\":\"Failed to unlink socket file\",\"attr\":{\"path\":\"/tmp/mongodb-27017.sock\",\"error\":\"Permission denied\"}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.262+03:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23091, \"ctx\":\"initandlisten\",\"msg\":\"Fatal assertion\",\"attr\":{\"msgid\":40486,\"file\":\"src/mongo/transport/transport_layer_asio.cpp\",\"line\":1120}}\n{\"t\":{\"$date\":\"2022-10-07T19:11:33.262+03:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23092, \"ctx\":\"initandlisten\",\"msg\":\"\\n\\n***aborting after fassert() failure\\n\\n\"}\n"}, {"role": "assistant", "content": "Text:It says failed to unlink tmp .socket file.Check permissions/ownership of this file\nMost likely owned by root from your previous run\nYou have to remove this file and start service again\nAlso make sure your dbpath directory is empty and has appropriate permissions on it for mongod to write onto it\nCode:"}, {"role": "user", "content": "Text:Most likely owned by root from your previous runWhat file should I remove? How can I change the root? How do I change the permissions mongod to write?\nCode:"}, {"role": "assistant", "content": "Text:Check\nls -lrt /tmp/mongod-27017.sock\nls -lrt /usr/\u2026/\u2026/mongodb\nCode:"}, {"role": "assistant", "content": "Text:As Ramacchandra states, the socket file is most likely owned by the root user and can safely be removed by running sudo rm /tmp/mongod-27017.sock.One thing I notice is that in your brew services lists output it shows the user of mongodb-community as root. You should be installing and running MongoDB as your regular user. The MongoDB process should never be run as the root user unless you are directed to by MongoDB support team for troubleshooting, and even then only if you understand the implications of what happens when you run the service as the root user. This could lead to privilege escalation which could then lead to bad things happening.\nCode:rootsudo rm /tmp/mongod-27017.sockbrew services listsmongodb-communityrootrootroot"}, {"role": "user", "content": "Text:I get this when I write something like @Ramachandra_Tummala said.I don\u2019t know what installing as a regular user means. I deleted the mongo and reinstalled it many times. Nothing works.This is the situation right now. I thought I have removed the file but whenever I write this command, the result show up.UPDATEI found the .sock file and deleted it with sudo rmHowever this time I get the error below;And now this is the log;I just dont even know what is going on at this point. All I ever wanted to do is setting up an environment an start my backend tutorial. I dont know if this is normal or not but I\u2019m not sure if I ever use Mongo again.Do you guys know why doesn\u2019t anything work? Or any suggestion?\nCode:macbook@SamsMacbook ~ % sudo rm /tmp/mongod-27017.sock.\nPassword:\nrm: /tmp/mongod-27017.sock.: No such file or directory\nmacbook@SamsMacbook ~ % ls -lrt /usr/local/var/mongodb \ntotal 0\nmacbook@SamsMacbook Library % ls -l /tmp/mongodb-27017.sock\nsrwx------ 1 root wheel 0 7 Eki 18:44 /tmp/mongodb-27017.sock\nmacbook@SamsMacbook ~ % ls -l /tmp/mongodb-27017.sock\nsrwx------ 1 root wheel 0 7 Oct 18:44 /tmp/mongodb-27017.sock\nsudo rmmacbook@SamsMacbook ~ % brew services list\nName Status User File\nmongodb-community error 25600 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist\nmacbook@SamsMacbook /tmp % brew services list \nName Status User File\nmongodb-community error 25600 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist\nmacbook@SamsMacbook /tmp % tail $(brew --prefix)/var/log/mongodb/mongo.log\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.399+03:00\"},\"s\":\"I\", \"c\":\"ASIO\", \"id\":22582, \"ctx\":\"MigrationUtil-TaskExecutor\",\"msg\":\"Killing all outstanding egress activity.\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.399+03:00\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784923, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the ServiceEntryPoint\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.399+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784925, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down free monitoring\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.399+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784927, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the HealthLog\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.399+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784928, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the TTL monitor\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.400+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":6278511, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the Change Stream Expired Pre-images Remover\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.400+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784929, \"ctx\":\"initandlisten\",\"msg\":\"Acquiring the global lock for shutdown\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.400+03:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4784931, \"ctx\":\"initandlisten\",\"msg\":\"Dropping the scope cache for shutdown\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.400+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20565, \"ctx\":\"initandlisten\",\"msg\":\"Now exiting\"}\n{\"t\":{\"$date\":\"2022-10-08T16:45:24.400+03:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23138, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down\",\"attr\":{\"exitCode\":100}}\n"}, {"role": "user", "content": "Text:Killing all outstanding egress activity.\"Hello guys,I have solved the problem.When the error was error 3584, what I did was to delete the 27017.sock file as you have said before.\nI did this using these commands one by one; (I\u2019m sure there are easier ways but I wanted to see everything clearly.)And then restarted the mongo.macbook@SamsMacbook ~ % brew services restart mongodb-communityI saw this error when I check if it is working properly or not.I have learned that this is caused because of the .conf file details. How to reach it? Easy.macbook@SamsMacbook ~ % open /usr/local/etc/mongod.confThe file includes some code like this;See if there is different than the one I shared above. My dbPath was empty. I changed it to the default value I found in the internet. dbPath: /usr/local/var/mongodbAnd then, we commandbrew services restart mongodb-communityThat\u2019s all folks! These are the solutions for error 3584 and error 25600 in Mongo.Thanks @Doug_Duncan and @Ramachandra_Tummala\nCode:Killing all outstanding egress activity.\"macbook@SamsMacbook ~ % cd /tmp\nmacbook@SamsMacbook /tmp % ls -a\nmacbook@SamsMacbook /tmp % sudo rm mongodb-27017.sock\nmacbook@SamsMacbook ~ % brew services restart mongodb-communitymacbook@SamsMacbook ~ % brew services list\nName Status User File\nmongodb-community error 25600 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist\nmacbook@SamsMacbook ~ % open /usr/local/etc/mongod.confsystemLog:\n destination: file\n path: /usr/local/var/log/mongodb/mongo.log\n logAppend: true\nstorage:\n dbPath: /usr/local/var/mongodb\nnet:\n bindIp: 127.0.0.1, ::1\n ipv6: true\n dbPath: /usr/local/var/mongodbbrew services restart mongodb-community"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Single node replicaset never finishing instanciating Error: \"Cannot use non-local read concern until replica set is finished initializing\" and tags: ['replication', 'transactions', 'containers']"}, {"role": "user", "content": "Text:Hello,I\u2019m trying to setup a mongodb replicaset as a single node in a docker container because I need to use the transactions to watch over changes in collections.The issue I\u2019m having is that the replicaset seems to never finish to instanciate and the loog display the following line every seconds:I\u2019ve tried every tutorials I\u2019ve found, every stackoverflow issue, they all say the same thing, the configuration should be fairly simple and work with what I have now.Here\u2019s my configurations:mongo-init.js (I removed the db and collection creation in hope to make it work)Dockerfile (I use a custom image because I\u2019m on docker windows and I can\u2019t set proper file permission on a file if I mount it in the container from the host. It\u2019s a POC security is not a concern anyway)docker-compose.ymlI did read the official documentation and I see no functionnal difference, I\u2019m really banging my head against a wall here trying to figure out what I did wrong?\nCode:{\"t\":{\"$date\":\"2022-05-19T21:31:57.421+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":9200}}\nconst rsconf = {\n _id: \"rs0\",\n members: [\n {\n _id: 0,\n host: '127.0.0.1:27017',\n },\n ]\n};\n\nrs.initiate(rsconf);\nFROM mongo:latest\nCOPY mongo/mongo-conf/mongodb.key /mongodb.key\nRUN chmod 600 /mongodb.key\nRUN chown 999:999 /mongodb.key\n\n# To solve \"Unable to open() file /home/mongodb/.dbshell - source: https://github.com/docker-library/mongo/issues/323#issuecomment-494648458\nRUN mkdir \"/home/mongodb\"\nRUN touch \"/home/mongodb/.dbshell\"\nRUN chown -R 999:999 /home/mongodb\n\nENTRYPOINT [\"docker-entrypoint.sh\"]\nversion: '3.8'\nservices:\n # Mongodb database\n mongo:\n image: mongo-custom\n container_name: mongo\n command: --bind_ip_all --replSet rs0 --keyFile /mongodb.key\n # restart: unless-stopped\n environment:\n MONGO_INITDB_ROOT_USERNAME: mogoadm\n MONGO_INITDB_ROOT_PASSWORD: mogopwd\n ports:\n - \"27017:27017\"\n volumes:\n - ./mongo/database/mongodb/db:/data/db\n - ./mongo/mongo-init:/docker-entrypoint-initdb.d:ro\n"}, {"role": "assistant", "content": "Text:It is failing at rs.initiate step\nCheck your syntax.I see additional commas in your rsconfSample:\nconfig={\"_id\":\u201crs0\u201d, \u201cmembers\u201d:[{\"_id\":0,\u201chost\u201d:\u201cmyhost:27017\u201d}]}\nrs.initiate(config)\nCode:"}, {"role": "user", "content": "Text:Hello, thank for your anwser, as per your sample I removed the extra commas and tried with and without double quotes on the keys but this resulted in no changes in the error unfortunately.I tried:and :to no result.This is the sample config for the official documentation, I\u2019m strugling to see what is wrong with my syntax compared to this:\nCode:const rsconf = {\n _id: \"rs0\",\n members: [\n {\n _id: 0,\n host: \"127.0.0.1:27017\"\n }\n ]\n}\nconst rsconf = {\n \"_id\": \"rs0\",\n \"members\": [\n {\n \"_id\": 0,\n \"host\": \"127.0.0.1:27017\"\n }\n ]\n}\nrs.initiate( {\n _id : \"rs0\",\n members: [\n { _id: 0, host: \"mongodb0.example.net:27017\" },\n { _id: 1, host: \"mongodb1.example.net:27017\" },\n { _id: 2, host: \"mongodb2.example.net:27017\" }\n ]\n})\n"}, {"role": "assistant", "content": "Text:mongo-init.jsHow exactly this mongo-init.js is run?\nI have read in one of the post which uses docker setup there should be a sleep after running the rs.initiate().There should be a gap before running next scripts like connecting to mongo.Check our forum threadsAlso why don\u2019t you try just rs.initiate() without any cfg variable\nIt will take default configuration\nCode:"}, {"role": "user", "content": "Text:The mongo-init.js is ran by being mounted into /docker-entrypoint-initdb.d in the mongo container.\nI belive it\u2019s automatically executed at database init when the container is started.I know it works because I use it for the database and collection creation with no issues (I commented thoses out for replicaset debug)I just tryed to put a sleep(10000) just after the rs.initiate(), but the container init didn\u2019t even reach it, I belive the rs.initiate never ended.I tried the rs.initiate() without any configuration, unfortunatelly that didn\u2019t change anything. (I also tried to put the config directly in the rs.initiate, in a const, var\u2026 All with no changes)Here\u2019s the full log I get when I start the container:After that the mongo just log the same error and increase the time between retries.\nCode:/docker-entrypoint-initdb.d{\"t\":{\"$date\":\"2022-05-21T16:15:18.997+00:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915701, \"ctx\":\"thread1\",\"msg\":\"Initialized wire specification\",\"attr\":{\"spec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":13},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":13},\"outgoing\":{\"minWireVersion\":0,\"maxWireVersion\":13},\"isInternalClient\":true}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:18.997+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23285, \"ctx\":\"thread1\",\"msg\":\"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:18.999+00:00\"},\"s\":\"W\", \"c\":\"ASIO\", \"id\":22601, \"ctx\":\"thread1\",\"msg\":\"No TransportLayer configured during NetworkInterface startup\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:18.999+00:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4648601, \"ctx\":\"thread1\",\"msg\":\"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize.\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.075+00:00\"},\"s\":\"W\", \"c\":\"ASIO\", \"id\":22601, \"ctx\":\"thread1\",\"msg\":\"No TransportLayer configured during NetworkInterface startup\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.075+00:00\"},\"s\":\"W\", \"c\":\"ASIO\", \"id\":22601, \"ctx\":\"thread1\",\"msg\":\"No TransportLayer configured during NetworkInterface startup\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.075+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationDonorService\",\"ns\":\"config.tenantMigrationDonors\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.076+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"thread1\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"ns\":\"config.tenantMigrationRecipients\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.076+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"thread1\",\"msg\":\"Multi threading initialized\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.077+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":1,\"port\":27017,\"dbPath\":\"/data/db\",\"architecture\":\"64-bit\",\"host\":\"mongo-sitac\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.077+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"5.0.8\",\"gitVersion\":\"c87e1c23421bf79614baf500fda6622bd90f674e\",\"openSSLVersion\":\"OpenSSL 1.1.1f 31 Mar 2020\",\"modules\":[],\"allocator\":\"tcmalloc\",\"environment\":{\"distmod\":\"ubuntu2004\",\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.077+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Ubuntu\",\"version\":\"20.04\"}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.077+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{\"net\":{\"bindIp\":\"*\"},\"replication\":{\"replSet\":\"rs0\"},\"security\":{\"keyFile\":\"/mongodb.key\"},\"storage\":{\"dbPath\":\"/data/db\",\"journal\":{\"enabled\":true}}}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:19.083+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22315, \"ctx\":\"initandlisten\",\"msg\":\"Opening WiredTiger\",\"attr\":{\"config\":\"create,cache_size=5855M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress,compact_progress],\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.240+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22430, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger message\",\"attr\":{\"message\":\"[1653149724:240959][1:0x7fc3a4f91c80], txn-recover: [WT_VERB_RECOVERY_ALL] Set global recovery timestamp: (0, 0)\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.241+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22430, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger message\",\"attr\":{\"message\":\"[1653149724:241029][1:0x7fc3a4f91c80], txn-recover: [WT_VERB_RECOVERY_ALL] Set global oldest timestamp: (0, 0)\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.255+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4795906, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger opened\",\"attr\":{\"durationMillis\":5172}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.255+00:00\"},\"s\":\"I\", \"c\":\"RECOVERY\", \"id\":23987, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger recoveryTimestamp\",\"attr\":{\"recoveryTimestamp\":{\"$timestamp\":{\"t\":0,\"i\":0}}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.279+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4366408, \"ctx\":\"initandlisten\",\"msg\":\"No table logging settings modifications are required for existing WiredTiger tables\",\"attr\":{\"loggingEnabled\":false}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.279+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22262, \"ctx\":\"initandlisten\",\"msg\":\"Timestamp monitor starting\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.298+00:00\"},\"s\":\"W\", \"c\":\"CONTROL\", \"id\":22138, \"ctx\":\"initandlisten\",\"msg\":\"You are running this process as the root user, which is not recommended\",\"tags\":[\"startupWarnings\"]}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.298+00:00\"},\"s\":\"W\", \"c\":\"CONTROL\", \"id\":22178, \"ctx\":\"initandlisten\",\"msg\":\"/sys/kernel/mm/transparent_hugepage/enabled is 'always'. We suggest setting it to 'never'\",\"tags\":[\"startupWarnings\"]}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.300+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":5071100, \"ctx\":\"initandlisten\",\"msg\":\"Clearing temp directory\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.301+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20536, \"ctx\":\"initandlisten\",\"msg\":\"Flow Control is enabled on this deployment\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.302+00:00\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":20997, \"ctx\":\"initandlisten\",\"msg\":\"Refreshed RWC defaults\",\"attr\":{\"newDefaults\":{}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.303+00:00\"},\"s\":\"I\", \"c\":\"FTDC\", \"id\":20625, \"ctx\":\"initandlisten\",\"msg\":\"Initializing full-time diagnostic data capture\",\"attr\":{\"dataDirectory\":\"/data/db/diagnostic.data\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.303+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20320, \"ctx\":\"initandlisten\",\"msg\":\"createCollection\",\"attr\":{\"namespace\":\"local.startup_log\",\"uuidDisposition\":\"generated\",\"uuid\":{\"uuid\":{\"$uuid\":\"fc624045-215e-4036-986b-91064e9f63b5\"}},\"options\":{\"capped\":true,\"size\":10485760}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.326+00:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":20345, \"ctx\":\"initandlisten\",\"msg\":\"Index build: done building\",\"attr\":{\"buildUUID\":null,\"namespace\":\"local.startup_log\",\"index\":\"_id_\",\"commitTimestamp\":null}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.327+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":6015317, \"ctx\":\"initandlisten\",\"msg\":\"Setting new configuration state\",\"attr\":{\"newState\":\"ConfigStartingUp\",\"oldState\":\"ConfigPreStart\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.327+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"ReadConcernMajorityNotAvailableYet: Read concern majority reads are currently not possible.\",\"nextWakeupMillis\":200}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.327+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4280500, \"ctx\":\"initandlisten\",\"msg\":\"Attempting to create internal replication collections\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.327+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20320, \"ctx\":\"initandlisten\",\"msg\":\"createCollection\",\"attr\":{\"namespace\":\"local.replset.oplogTruncateAfterPoint\",\"uuidDisposition\":\"generated\",\"uuid\":{\"uuid\":{\"$uuid\":\"d2489be1-fa14-4def-8a30-7b93eb5416a6\"}},\"options\":{}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.363+00:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":20345, \"ctx\":\"initandlisten\",\"msg\":\"Index build: done building\",\"attr\":{\"buildUUID\":null,\"namespace\":\"local.replset.oplogTruncateAfterPoint\",\"index\":\"_id_\",\"commitTimestamp\":null}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.363+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20320, \"ctx\":\"initandlisten\",\"msg\":\"createCollection\",\"attr\":{\"namespace\":\"local.replset.minvalid\",\"uuidDisposition\":\"generated\",\"uuid\":{\"uuid\":{\"$uuid\":\"b80857d3-271d-45ac-bdab-e5178caf07c5\"}},\"options\":{}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.393+00:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":20345, \"ctx\":\"initandlisten\",\"msg\":\"Index build: done building\",\"attr\":{\"buildUUID\":null,\"namespace\":\"local.replset.minvalid\",\"index\":\"_id_\",\"commitTimestamp\":null}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.394+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20320, \"ctx\":\"initandlisten\",\"msg\":\"createCollection\",\"attr\":{\"namespace\":\"local.replset.election\",\"uuidDisposition\":\"generated\",\"uuid\":{\"uuid\":{\"$uuid\":\"fb02e9bd-0ddd-4590-80ed-b65d641bc8dd\"}},\"options\":{}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.445+00:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":20345, \"ctx\":\"initandlisten\",\"msg\":\"Index build: done building\",\"attr\":{\"buildUUID\":null,\"namespace\":\"local.replset.election\",\"index\":\"_id_\",\"commitTimestamp\":null}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.445+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4280501, \"ctx\":\"initandlisten\",\"msg\":\"Attempting to load local voted for document\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.445+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":21311, \"ctx\":\"initandlisten\",\"msg\":\"Did not find local initialized voted for document at startup\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.445+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4280502, \"ctx\":\"initandlisten\",\"msg\":\"Searching for local Rollback ID document\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.445+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":21312, \"ctx\":\"initandlisten\",\"msg\":\"Did not find local Rollback ID document at startup. Creating one\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.445+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20320, \"ctx\":\"initandlisten\",\"msg\":\"createCollection\",\"attr\":{\"namespace\":\"local.system.rollback.id\",\"uuidDisposition\":\"generated\",\"uuid\":{\"uuid\":{\"$uuid\":\"d2872c85-c392-4bf3-ab91-f2c13bbd1309\"}},\"options\":{}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.480+00:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":20345, \"ctx\":\"initandlisten\",\"msg\":\"Index build: done building\",\"attr\":{\"buildUUID\":null,\"namespace\":\"local.system.rollback.id\",\"index\":\"_id_\",\"commitTimestamp\":null}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.480+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":21531, \"ctx\":\"initandlisten\",\"msg\":\"Initialized the rollback ID\",\"attr\":{\"rbid\":1}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.480+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":21313, \"ctx\":\"initandlisten\",\"msg\":\"Did not find local replica set configuration document at startup\",\"attr\":{\"error\":{\"code\":47,\"codeName\":\"NoMatchingDocument\",\"errmsg\":\"Did not find replica set configuration document in local.system.replset\"}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.480+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":6015317, \"ctx\":\"initandlisten\",\"msg\":\"Setting new configuration state\",\"attr\":{\"newState\":\"ConfigUninitialized\",\"oldState\":\"ConfigStartingUp\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.481+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20320, \"ctx\":\"initandlisten\",\"msg\":\"createCollection\",\"attr\":{\"namespace\":\"local.system.views\",\"uuidDisposition\":\"generated\",\"uuid\":{\"uuid\":{\"$uuid\":\"4243d9cb-9af0-48fc-8dc2-187c55ed53d8\"}},\"options\":{}}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.514+00:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":20345, \"ctx\":\"initandlisten\",\"msg\":\"Index build: done building\",\"attr\":{\"buildUUID\":null,\"namespace\":\"local.system.views\",\"index\":\"_id_\",\"commitTimestamp\":null}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.517+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20714, \"ctx\":\"LogicalSessionCacheRefresh\",\"msg\":\"Failed to refresh session cache, will try again at the next refresh interval\",\"attr\":{\"error\":\"NotYetInitialized: Replication has not yet been configured\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.517+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":40440, \"ctx\":\"initandlisten\",\"msg\":\"Starting the TopologyVersionObserver\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.517+00:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20712, \"ctx\":\"LogicalSessionCacheReap\",\"msg\":\"Sessions collection is not set up; waiting until next sessions reap interval\",\"attr\":{\"error\":\"NamespaceNotFound: config.system.sessions does not exist\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.517+00:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":40445, \"ctx\":\"TopologyVersionObserver\",\"msg\":\"Started TopologyVersionObserver\"}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.518+00:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":23015, \"ctx\":\"listener\",\"msg\":\"Listening on\",\"attr\":{\"address\":\"/tmp/mongodb-27017.sock\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.518+00:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":23015, \"ctx\":\"listener\",\"msg\":\"Listening on\",\"attr\":{\"address\":\"0.0.0.0\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.518+00:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":23016, \"ctx\":\"listener\",\"msg\":\"Waiting for connections\",\"attr\":{\"port\":27017,\"ssl\":\"off\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.528+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":400}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:24.928+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":600}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:25.528+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":800}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:26.329+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":1000}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:27.330+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":1200}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:28.532+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":1400}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:29.933+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":1600}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:31.535+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":1800}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:33.337+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":2000}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:35.339+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":2200}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:37.542+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":2400}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:39.945+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":2600}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:42.548+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":2800}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:45.351+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":3000}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:48.354+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":3200}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:51.558+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":3400}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:54.962+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":3600}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:15:58.565+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":3800}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:02.370+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":4000}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:06.373+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":4200}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:10.578+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":4400}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:14.983+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":4600}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:19.588+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":4800}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:24.306+00:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22430, \"ctx\":\"Checkpointer\",\"msg\":\"WiredTiger message\",\"attr\":{\"message\":\"[1653149784:306812][1:0x7fc39c77f700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 55, snapshot max: 55 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 1\"}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:24.393+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":5000}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:29.399+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":5200}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:34.605+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":5400}}\n\n{\"t\":{\"$date\":\"2022-05-21T16:16:40.010+00:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4939300, \"ctx\":\"monitoring-keys-for-HMAC\",\"msg\":\"Failed to refresh key cache\",\"attr\":{\"error\":\"NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.\",\"nextWakeupMillis\":5600}}\n"}, {"role": "assistant", "content": "Text:same error for me and i am struggling to find answer. It runs on jenkins but no way to pass this step even you use &\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Fatal error: Uncaught Error: Class \u2018MongoDB\\Driver\\Manager\u2019 and tags: ['connecting', 'atlas-cluster', 'php']"}, {"role": "user", "content": "Text:Hello, I am trying to connect via the PHP driver. I have followed the installation procedures from MongoDB\u2019s PHP Driver documentation regarding pecl install for the extension and composer install of mongodb into the root directory.I have used the below code to launch the php driver and establish the connection to the database (note that I did change the inputs for db, pass, and cluster in the actual code).However, when I run this, I receive the following fatal error:Fatal error : Uncaught Error: Class \u2018MongoDB\\Driver\\Manager\u2019 not found in /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/vendor/mongodb/mongodb/src/Client.php:124 Stack trace: #0 /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/conf.php(6): MongoDB\\Client->__construct(\u2018mongodb+srv://c\u2026\u2019) #1 /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/mongodb.php(28): require_once(\u2019/home3/coradase\u2026\u2019) #2 /home3/coradase/public_html/cora-staging/wp-includes/class-wp-hook.php(307): cora_mongodb_admin_page(\u2019\u2019) #3 /home3/coradase/public_html/cora-staging/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters(\u2019\u2019, Array) #4 /home3/coradase/public_html/cora-staging/wp-includes/plugin.php(476): WP_Hook->do_action(Array) #5 /home3/coradase/public_html/cora-staging/wp-admin/admin.php(259): do_action(\u2018toplevel_page_c\u2026\u2019) #6 {main} thrown in /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/vendor/mongodb/mongodb/src/Client.php on line 124Client.php (the file referenced in the error code) is a default file that came with the Composer installation. I have not edited the file. The function in Client.php that contains line 124 (referenced in the error) is shown below:For reference, line 124 is:\n$this->manager = new Manager($uri, $uriOptions, $driverOptions);Again, this code comes directly from the composer installation of mongodb, and has not been edited at all.I appreciate any insight form the team or anyone who has had this same problem in trying to debug so that the code will properly establish the connection to the database.Thank you!\nCode::@.lkffbtl.mongodb.net/?retryWrites=true&w=majority');\n\nvar_dump( $client );\n public function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])\n {\n $driverOptions += ['typeMap' => self::$defaultTypeMap];\n\n if (! is_array($driverOptions['typeMap'])) {\n throw InvalidArgumentException::invalidType('\"typeMap\" driver option', $driverOptions['typeMap'], 'array');\n }\n\n if (isset($driverOptions['autoEncryption']['keyVaultClient'])) {\n if ($driverOptions['autoEncryption']['keyVaultClient'] instanceof self) {\n $driverOptions['autoEncryption']['keyVaultClient'] = $driverOptions['autoEncryption']['keyVaultClient']->manager;\n } elseif (! $driverOptions['autoEncryption']['keyVaultClient'] instanceof Manager) {\n throw InvalidArgumentException::invalidType('\"keyVaultClient\" autoEncryption option', $driverOptions['autoEncryption']['keyVaultClient'], [self::class, Manager::class]);\n }\n }\n\n $driverOptions['driver'] = $this->mergeDriverInfo($driverOptions['driver'] ?? []);\n\n $this->uri = (string) $uri;\n $this->typeMap = $driverOptions['typeMap'] ?? null;\n\n unset($driverOptions['typeMap']);\n\n $this->manager = new Manager($uri, $uriOptions, $driverOptions);\n $this->readConcern = $this->manager->getReadConcern();\n $this->readPreference = $this->manager->getReadPreference();\n $this->writeConcern = $this->manager->getWriteConcern();\n }\n$this->manager = new Manager($uri, $uriOptions, $driverOptions);"}, {"role": "assistant", "content": "Text:Did you remember to add the line extension=mongodb.so to the end of your /etc/php/8.1/cli/php.ini or whatever ini file is appropriate to your php installation?\nCode:extension=mongodb.so/etc/php/8.1/cli/php.ini"}, {"role": "user", "content": "Text:Hi Jack - yes, I did add the extension line to php.ini.For reference, I am trying to connect MongoDB to a web app running on Wordpress.\nCode:"}, {"role": "assistant", "content": "Text:Well, what\u2019s happening is that the classes built into the mongodb.so are not being found. Whatever the reason. Try loading php at the command line \u2026Then ctl-D to exit and PHP should spew a lot of configuration info.\nLook for lines like:and if you don\u2019t find them, then the extension is not being loaded.\nCode:$ php\n\nmongodb\n\nMongoDB support => enabled\nMongoDB extension version => 1.14.0\nMongoDB extension stability => stable\nlibbson bundled version => 1.22.0\nlibmongoc bundled version => 1.22.0\nlibmongoc SSL => enabled\nlibmongoc SSL library => OpenSSL\nlibmongoc crypto => enabled\nlibmongoc crypto library => libcrypto\nlibmongoc crypto system profile => disabled\nlibmongoc SASL => disabled\nlibmongoc ICU => enabled\nlibmongoc compression => enabled\nlibmongoc compression snappy => disabled\nlibmongoc compression zlib => enabled\nlibmongoc compression zstd => disabled\nlibmongocrypt bundled version => 1.5.0\nlibmongocrypt crypto => enabled\nlibmongocrypt crypto library => libcrypto\n"}, {"role": "assistant", "content": "Text:Hi\nMy extension have loaded, but get the same error. Also, I want to have connect in local db (it seems runing on 127.0.1.1) - what connection string should I use?\nCode:"}, {"role": "assistant", "content": "Text:what connection string should I use?mongodb://user:password should be good enough assuming you really mean 127.0.0.1\nCode:mongodb://user:password"}, {"role": "assistant", "content": "Text:Thanks for reply, but problem is still here\nI use mongodb from another application and its connecting without prompt and also located in 127.0.1.1 (I use command mongodb --host 127.0.1.1) And in php file its:\n$client = new MongoDB\\Driver\\Manager(\u2018mongodb://127.0.1.1\u2019);\nI try to change file Client.php with manually adding \u201c127.0.1.1\u201d, but it doesn`t work too\nCode:s connecting without prompt and also located in 127.0.1.1 (I use command mongodb --host 127.0.1.1) And in php file it"}, {"role": "assistant", "content": "Text:I\u2019ve just tried to create a free DB on Atlas and I\u2019ve used the string from docs$serverApi = new ServerApi(ServerApi::V1); $client = new MongoDB\\Client( 'mongodb+srv://user:@.mongodb.net/?retryWrites=true&w=majority', [], ['serverApi' => $serverApi]); $db = $client->test;I have the same problem, so it\u2019s something with mongodb/compose deployment\nCode:$serverApi = new ServerApi(ServerApi::V1); $client = new MongoDB\\Client( 'mongodb+srv://user:@.mongodb.net/?retryWrites=true&w=majority', [], ['serverApi' => $serverApi]); $db = $client->test;"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Can't connect to MongoDB Atlas - querySrv ENOTFOUND and tags: ['connecting']"}, {"role": "user", "content": "Text:Hi all,First of all, if this is not the right category, please let me know which one is.I\u2019m new to MongoDB. Made a local deploy and it\u2019s running fine. Now I\u2019m trying to set up an Atlas instance, but can\u2019t seem to be able to connect to it.\nI\u2019m trying to use the stringmongodb+srv://pdantas:@cluster0.n2hlh.mongodb.net/testas suggested in the \u201cconnect\u201d session in Atlas console, however, when I enter this string in Compass I get the errorquerySrv ENOTFOUND _mongodb._tcp.cluster0.n2hlh.mongodb.netI\u2019ve also tried connecting through mongosh and get the same errorC:\\Users\\OS16S8898>mongosh \u201cmongodb+srv://cluster0.c0tbu.mongodb.net/myFirstDatabase\u201d --username pdantas\nEnter password: *******\nCurrent Mongosh Log ID: 6165e8a56936fb42f0cbf229\nConnecting to: mongodb+srv://cluster0.c0tbu.mongodb.net/myFirstDatabase\nError: querySrv ENOTFOUND _mongodb._tcp.cluster0.c0tbu.mongodb.netI\u2019ve whitelisted my IP, and even added 0.0.0.0/0 to the IP access list, to no avail. Can someone please help me find out what is it that I\u2019m doing wrong?Thanks!\nCode:"}, {"role": "assistant", "content": "Text:Hi @Pedro_Dantas,Which versions are you using?Also, this topic had a solution: https://www.mongodb.com/community/forums/t/readme-running-application-error-querysrv-enotfound-solved/85196/3Does it work for you too?\nCode:"}, {"role": "assistant", "content": "Text:Try using google\u2019s DNS 8.8.8.8 and 8.8.4.4.See Public DNS \u00a0|\u00a0 Google Developers for more details.\nCode:"}, {"role": "user", "content": "Text:Hi @MaBeuLux88.Those were the latest versions that I could find.About the solution detailed in the link, I tried formatting the string as instructed (using the mongodb protocol and a lista of the URLs for each shard separated by a comma) but still can\u2019t get a connection (it does seem to be able to resolve the IP address, though).Am I still missing something?Thanks.\nCode:C:\\Users\\OS16S8898>mongosh mongodb://pdantas:pdantas@cluster0-shard-00-00.c0tbu.mongodb.net:27017,cluster0-shard-00-01.c0tbu.mongodb.net:27017,cluster0-shard-00-02.c0tbu.mongodb.net:27017/test\nCurrent Mongosh Log ID: 6166f8446f2747e87b767609\nConnecting to: mongodb://@cluster0-shard-00-00.c0tbu.mongodb.net:27017,cluster0-shard-00-01.c0tbu.mongodb.net:27017,cluster0-shard-00-02.c0tbu.mongodb.net:27017/test\nMongoServerSelectionError: connection to 108.129.24.16:27017 closed\n"}, {"role": "user", "content": "Text:Hi @steevej I added those IP\u2019s to the whitelist but nothing happened, was I supposed to do something else?Thanks.\nCode:"}, {"role": "assistant", "content": "Text:I added those IP\u2019s to the whitelistThe 2 IPs I provided are not at all related to the white list of your cluster. It has to do with host name resolution, aka DNS. In the link I provided you will find instructions forConfigure your network settings to use the IP addresses 8.8.8.8 and 8.8.4.4 as your DNS servers.Your ISP or VPN provider probably uses old DNS software that cannot resolve SRV connection strings.I have just notice that your original post contains 2 different connection strings, one with c0tbu and one with n2hlh.\nCode:"}, {"role": "assistant", "content": "Text:Make sure to retrieve the Compass connection string from the MongoDB Atlas UI like this:\nimage605\u00d7725 43.8 KB\n\nimage1356\u00d71180 113 KB\n\nimage1357\u00d71146 101 KB\nOf course make sure to change the values for the username and password.\nThey come from this menu. It\u2019s not the Atlas user/pwd.\nimage312\u00d7504 17.2 KB\nIn the end, it should look like this:Try to connect using the above connection string in Compass to see if it works. This is the public cluster where I\u2019m hosting the Open Data COVID-19 data set.If that doesn\u2019t work - then you have a DNS problem like @steevej explained and you have to add 8.8.8.8 and/or 8.8.4.4 in your DNS list.For me on linux, I would have to add on the first line of /etc/resolv.conf:Cheers,\nMaxime.\nCode:mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/test\n/etc/resolv.confnameserver 8.8.8.8\n\n"}, {"role": "user", "content": "Text:Hi guys,I was already using the connection string provided by the Atlas console, to no avail.\nI changed the DNS to Google\u2019sbut it\u2019s still not working\nimage692\u00d7177 9.08 KB\nI also tried to connect to the Covid19 DB as suggested by Maxime but get the same error.However, I found out that I do can connect through mongoshell So I\u2019m guessing I can work through here, but if you have any further idea on why the connection though Compass isn\u2019t working I\u2019d love to hear, as I\u2019d rather work that way if possible.Thanks for the assistance so far PD\nCode:SSID:\tPivonet 5G\nProtocol:\tWi-Fi 5 (802.11ac)\nSecurity type:\tWPA2-Personal\nNetwork band:\t5 GHz\nNetwork channel:\t100\nIPv6 address:\t2001:818:e348:c700:2093:b4f9:eef:80a8\nLink-local IPv6 address:\tfe80::2093:b4f9:eef:80a8%19\nIPv6 DNS servers:\t2001:4860:4860::8888\n2001:4860:4860::8844\nIPv4 address:\t192.168.1.143\nIPv4 DNS servers:\t8.8.8.8\n8.8.4.4\nManufacturer:\tIntel Corporation\nDescription:\tIntel(R) Wireless-AC 9560 160MHz\nDriver version:\t21.120.0.9\nPhysical address (MAC):\t84-C5-A6-6A-70-6B\nC:\\Users\\OS16S8898>mongosh mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/covid19\nCurrent Mongosh Log ID: 61680c1143666d0fa2a10a77\nConnecting to: mongodb+srv://@covid-19.hip2i.mongodb.net/covid19\nUsing MongoDB: 4.4.9\nUsing Mongosh: 1.1.0\n\nFor mongosh info see: https://docs.mongodb.com/mongodb-shell/\n\nAtlas covid-19-shard-0 [primary] covid19>\n"}, {"role": "assistant", "content": "Text:Can you connect toUsing MongoDB Compass?\nCode:mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/test\n"}, {"role": "user", "content": "Text:@MaBeuLux88 No, as I said I get the same error\nimage710\u00d7179 8.86 KB\n\nCode:"}, {"role": "assistant", "content": "Text:What\u2019s your OS & are you up-to-date ? Looks like there is definitely something wrong with your Internet connection. Are you behind a VPN maybe? Firewall? Or maybe it\u2019s just a DNS issue as @steevej suggested.\nCan you try a different internet connection & disable everything than can cause connection issues? Antivirus software can block connections sometimes as well. If it works reactive them one by one and eliminate the troublemaker !Cheers,\nMaxime.\nCode:"}, {"role": "assistant", "content": "Text:mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/testOn my side I was having the same issue and by disabling my VPN, the connection worked.Due to work, I need to use a VPN so how can we fix this issue other than disabling the VPN?\nCode:mongodb+srv://readonly:readonly@covid-19.hip2i.mongodb.net/test"}, {"role": "assistant", "content": "Text:Your work probably disabled connections to port 27017 or maybe they have even more restrictive rules in place. You need to talk to your IT support. Pity that your work system & network doesn\u2019t allow you to work . I guess they are just missing an exception on this port in their gateway rules. But I\u2019m not an expert .\nCode:"}, {"role": "assistant", "content": "Text:Your work probably disabled connections to port 27017Try http://portquiz.net:27017/ to see if it is the above.\nCode:"}, {"role": "assistant", "content": "Text:This is happening to me now after Windows automatically updated to version 10.0.19042 Build 19042.Last night things were working fine, got up today and my machine had restarted & updated. Skipped Windows 11 spam at startup, started up my dev environment in WSL1 like always, and now I can\u2019t work. Anyone else experiencing this?I can connect with Compass just fine.I\u2019m not connected to VPN (which does mess up connections to Atlas, although with a different error). Until today I have never seen the error in OP\u2019s post.telnet portquiz.net 27017 is failing, so I\u2019m guessing something in the Windows update affected Windows Defender.Couldn\u2019t ping google.com either.[SOLVED]This worked for me: edit /etc/wsl.conf and set generateResolvConf = true\n\n\n\n# Environment\n\n```none\nWindows build number: Version 10.0.18363.1256\nYour Distribution version: Both Ubuntu 18.04 and Ubuntu 20.04\nWhether the issue is on WSL 2 and/or WSL 1: WSL 2\n```\n\n# Steps to reproduce\nInstall WSL2 with any Ubuntu distro(1804/2004) .Ping google.com or any other website. Tried on with/without VPN(Big Edge IP client).\n\n\n\n\n\n\n\n**WSL logs**: \n**ping google.com**\nTemporary failure in name resolution\n\nFor **sudo apt update**\n\nErr:1 http://archive.ubuntu.com/ubuntu bionic InRelease\n Temporary failure resolving 'archive.ubuntu.com'\nErr:2 http://security.ubuntu.com/ubuntu bionic-security InRelease\n Temporary failure resolving 'security.ubuntu.com'\nErr:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease\n Temporary failure resolving 'archive.ubuntu.com'\nErr:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease\n Temporary failure resolving 'archive.ubuntu.com'\nReading package lists... Done\nBuilding dependency tree\nReading state information... Done\nAll packages are up to date.\nW: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic/InRelease Temporary failure resolving 'archive.ubuntu.com'\nW: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-updates/InRelease Temporary failure resolving 'archive.ubuntu.com'\nW: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-backports/InRelease Temporary failure resolving 'archive.ubuntu.com'\nW: Failed to fetch http://security.ubuntu.com/ubuntu/dists/bionic-security/InRelease Temporary failure resolving 'security.ubuntu.com'\nW: Some index files failed to download. They have been ignored, or old ones used instead.\n\n# Expected behavior\n\nI should get reply to the ping. And Internet should be easily accessible from within WSL.\n\nWSL 1 has no problem. I am able to connect to internet. When I try to use docker on WSL , it asks to upgrade to WSL2. So now i have no option. Just have to use WSL2 for docker where there is no internet connectivity\n\n\n\n# Actual behavior\n\n![image](https://user-images.githubusercontent.com/63879567/103714165-9f7cd300-4f83-11eb-906f-d2faf0e7f071.png)\n\n\nHave looked at the solutions from other issues. None seems to works. Follows some that I have tried but it seems not to work.\n\n1. Added (_[network]generateResolvConf = false_) to **wsl.conf** And add _nameserver 8.8.8.8_ in **resolv.conf**\n\n2. Run the following powershell script \n\n```\n`echo \"Restarting WSL Service\"\nRestart-Service LxssManager\necho \"Restarting Host Network Service\"\nStop-Service -name \"hns\"\nStart-Service -name \"hns\"\necho \"Restarting Hyper-V adapters\"\nGet-NetAdapter -IncludeHidden | Where-Object `\n {$_.InterfaceD```\nescription.StartsWith('Hyper-V Virtual Switch Extension Adapter')} `\n | Disable-NetAdapter -Confirm:$False\nGet-NetAdapter -IncludeHidden | Where-Object `\n {$_.InterfaceDescription.StartsWith('Hyper-V Virtual Switch Extension Adapter')} `\n | Enable-NetAdapter -Confirm:$False`\n```\n\n\nPlease let me know how can i fix this issue, so i can connect to internet from my WSL\n\nFYI Antivirus - McAffe and Windows Defender is enabled.\nCode:telnet portquiz.net 27017generateResolvConf = true"}, {"role": "assistant", "content": "Text:Thanks, here it worked.\nCode:"}, {"role": "assistant", "content": "Text:I have the same problem because I was connected to a VPN, when I disconnect it it works immediately.\nCode:"}, {"role": "assistant", "content": "Text:Having run into a host of issues using private endpoints, some or most self inflicted, I have come the assumption that the \u201cError: querySrv ENOTFOUND\u201d has to do with the inability of the driver to resolve a FQDN of the \u201cmongodb+srv\u201d to names of the replica set members.\nCode:"}, {"role": "assistant", "content": "Text:The error generally indicates the FQDN for the associated host(s) for the SRV record were not able to be resolved by the DNS in use.As of the time of this message, the SRV record prefix for Atlas clusters is _mongodb._tcp.Below is a reproduction that shows this error. Let\u2019s say I have a cluster which has an associated SRV record which resolves to the following hostnames:Although not exactly the case for all similar errors generated and only for demonstration purposes, I will pass through an invalid SRV record (to some degree attempt to mimic the DNS being unable to resolve the SRV records):Using the DNS seed list connection format with the invalid SRV record above in Compass results in the querySrv ENOTFOUND error:\nimage1242\u00d7624 52.5 KB\nIn conclusion, the error querySrv ENOTFOUND was caused by DNS resolving issues, likely from the client side. Also as several people have noted in this thread, if you\u2019re using VPN and encountering this issue only on the VPN (i.e. Connection works fine without querySRV error outside of the VPN connection) then it is probably due to how the VPN is configured. To my knowledge there are some VPN\u2019s which assign a new DNS for the VPN session which could result in this error.\nCode:_mongodb._tcp.nslookup -type=SRV _mongodb._tcp.cluster0.k0ke7qa.mongodb.net\n\n\nNon-authoritative answer:\n_mongodb._tcp.cluster0.k0ke7qa.mongodb.net\tservice = 0 0 27017 ac-omkxrjv-shard-00-00.k0ke7qa.mongodb.net.\n_mongodb._tcp.cluster0.k0ke7qa.mongodb.net\tservice = 0 0 27017 ac-omkxrjv-shard-00-01.k0ke7qa.mongodb.net.\n_mongodb._tcp.cluster0.k0ke7qa.mongodb.net\tservice = 0 0 27017 ac-omkxrjv-shard-00-02.k0ke7qa.mongodb.net.\nnslookup -type=SRV _mongodb._tcp.cluster0.abcdefg.mongodb.net\n\n\n** server can't find _mongodb._tcp.cluster0.abcdefg.mongodb.net: NXDOMAIN\nquerySrv ENOTFOUNDquerySrv ENOTFOUNDquerySRV"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Increase max document size to at least 64MB and tags: []"}, {"role": "user", "content": "Text:Initially limit was 4MB, then it was raised to 16MB in 2009.\nWe are in 2021, we have better hardware, better network, bigger documents and competitors without 16MB limit.\nThere are a ton of use cases where this limit is too small nowadays, sensors, large documents with history of data.\nI\u2019ve opened a new JIRA Issue on this here: https://jira.mongodb.org/browse/SERVER-60040\nCode:"}, {"role": "user", "content": "Text:Ticket on Jira has been closed with this comment: \u201c Thanks for your report. Please note that the SERVER project is for bugs for the MongoDB server. As this ticket appears to be an improvement request, I will now close it.\u201dBut main Jira page for MongoDB says:\n\u201c\nCode:"}, {"role": "assistant", "content": "Text:Hi @Ivan_Fioravanti welcome to the community!Apologies for the confusion. The description of the SERVER project is a bit outdated. We currently are using https://feedback.mongodb.com/ to collect ideas on how to improve the server, and dedicated the SERVER JIRA project for bug reports. Specifically in your case, you would want to go to the Database Section on that page.Best regards\nKevin\nCode:"}, {"role": "assistant", "content": "Text:Hi @Ivan_FioravantiSince only data that\u2019s always used together should be stored together, I\u2019m curious about the use case that requires documents bigger than 16MBs. You mention tons of use cases, but can you be a bit more specific? Like \u201chistory of data\u201d - this seems like a problematic example since eventually it will outgrow any document size limit, and I\u2019m not sure I can think of a use case where you need all history (no matter how old) when reading a document.Asya\nCode:"}, {"role": "user", "content": "Text:Hi @Asya_Kamsky\nthere are many examples in the https://jira.mongodb.org/browse/SERVER-5923\neveryone starts using MongoDB thinking: 16MB is a lot! I\u2019ll never hit this limit, but when you reach it is a mess.Also this one would be extremely beneficial https://jira.mongodb.org/browse/SERVER-12305 complex aggregations with many pipeline can hit this limit more often than you think.\nRemoving this limit shoild be easier, please plan at least this one.Thanks,\nIvan\nCode:"}, {"role": "assistant", "content": "Text:when you reach it is a messThat\u2019s because it usually is an indication of incorrect schema design.Asya\nCode:"}, {"role": "assistant", "content": "Text:I kindly disagree: I have financial data of a currency symbols like USDJPY (US-Dollar vs. Japan Yen) and USDCHF. Each daily candle contains a timestamp and 4 prices: open, high, low and close price.I\u2019ve been implementing mongo queries and complex analysis routines for many years and was - until now - happily using just one document per symbol. Just recently I figured out that from more than 3000 financial instruments USDJPY and USDCHF are the only ones that have such a huge data history (dating back to January 1970) that they exceed 16MB and thus cannot be stored entirely.With this 16MB limit I would now have to go through dozens of complicated methods and implement additional \u201cboilerplate\u201d logic to read in chunks of history data and deal with highly increased complexity of analysis routines that now need to see beyond the borders between a set of chunks. No fun, seriously.I do like to work with MongoDB and I don\u2019t mind difficult tasks, but implementing additional logic just because there is no way to increase a tightened memory \u201cbudget\u201d seems utterly wrong. At least to me. Not to mention that the whole additional logic reduces the readability of the code and lowers its performance.If there\u2019s chance, can you at least provide a parameter in MongoDB with the default of 16MB, and in case people really need more memory, then they have the freedom to do so?\nCode:"}, {"role": "assistant", "content": "Text:The only way to have larger document size would be to change the limit in the source code and to recompile/build it yourself and then run your own changed copy. I wouldn\u2019t recommend it though because there are a lot of other places where things can go wrong - drivers assuming documents will not be larger than 16MBs also.It\u2019s hard to imagine that it\u2019s actually required to have full history of a symbol in a single document. Do you always analyze the full history when querying it? If not then it\u2019s quite inefficient to keep it all on a single document.Asya\nCode:"}, {"role": "assistant", "content": "Text:Similar use case here\u2026I\u2019m using mongoDB to store colelctions of 10000 frames of a moving system of 200.000 particles. Each frame stores 13 floating-point values per particle. So a single frame holds 2.6 million floating point values (20.8 MB). It is just not practical to split frames into more than 1 document.I have 128 processors, 16 TB of SSD and 1 TB of RAM on the server\u2026 could anybody explain the logic behind the 16MB document limit?. Sounds a bit 2009.\nCode:"}, {"role": "assistant", "content": "Text:How are you using this data? Do you always fetch all 10000 frames of all the values? Sure, 16MBs is arbitrary, but 10 thousand seems arbitrary also, why not five thousand?Asya\nCode:"}, {"role": "assistant", "content": "Text:Hi Asya.For my case scenario, each frame is 2 picoseconds of motion. 10k frames are 20 nanoseconds, which is the minimum window I need to measure. Sampling less time would be statistically insufficient, and reducing sampling times would induce aliasing.After saving I need to build n-dimentioinal dataframes and do some physics with it. I\u2019m still thinking wether I should do pipelining or work everything from python.Would you go for GridFS? or definetly compile with max document size to\u2026 say 64Mb?.Best!\nPedro\nCode:"}, {"role": "assistant", "content": "Text:I don\u2019t fully understand the implications of forcing a bigger document size. Hence the question.As for the usage, i need to query each particle in all 10.000 frames and compute its motion. This can be done by getting all 13 attributes of the same particle ID from all documents (if each frame is 1 document).So 13x8x10000 is 1MB per particle. But then each 20MB frame should fit in a document.I\u2019m thinking splitting frame data in 2 collections would do\u2026 but its far from ideal.\nCode:"}, {"role": "assistant", "content": "Text:Mongo Manual saidwe can use embedded documents and arrays to capture relationships between data in a single document structure instead of normalizing across multiple documents and collections, this single-document atomicity obviates the need for multi-document transactions for many practical use cases.So we tend to use embed documents\uff0cbut sometimes one document can be very large\uff0cin our project it may reach 30M or more, so we must split it and keep reference relation, it gonna be very complicated and this way mongo doesn\u2019t support muti-doc txn in single server, it\u2019s so wired.\nRedis has supported RedisJson Module and the limit is 512M, I wish mongo increase this limit and support JsonPath.\nAnd i want to know why mongo only support muti-doc txn in replica and shard, sometimes we want to test transaction but mush deploy replica, it\u2019s troublesome\nCode:"}, {"role": "assistant", "content": "Text:mongo doesn\u2019t support muti-doc txn in single serverI\u2019m not sure what you are talking about - MongoDB has supported transactions (included across shards) for years now\u2026Asya\nCode:"}, {"role": "assistant", "content": "Text:i want to know why mongo only support muti-doc txn in replica and shard, sometimes we want to test transaction but mush deploy replica, it\u2019s troublesomeHi @timer_izaya,Multi-document transactions rely on the replication oplog which is not present on a standalone mongod deployment.However, you can deploy a single node replica set for test purposes.Regards,\nStennie\nCode:mongod"}, {"role": "assistant", "content": "Text:Don\u2019t you love it when a company tells you it\u2019s your business that\u2019s wrong, not their product.We have also crashed into the 16MB document size limit in another financial use case. The application design is sound, the issue is not the schema or the way in which we are using the tool. The issue is the tool, so we have little choice but to switch to another tool unfortunately.It seems that if multiple customers, in different industries, with very different use cases, are all struggling with the limitation it would be prudent for that company to ask whether it\u2019s really the customers who have gotten it wrong, instead of spikily insisting that they don\u2019t know what they are doing or don\u2019t understand their own domain.\nCode:"}, {"role": "assistant", "content": "Text:I have no choice but to implement a generic method to split huge json.\nCode:"}, {"role": "assistant", "content": "Text:Same here I have simple website builder where we keep pages for easy css and text manipulation.\nCode:"}, {"role": "assistant", "content": "Text:We\u2019re storing documents with images and lidar pointclouds, using MongoDB as a geospatial database. Each pose of the vehicle is stored as a geojson point and queried by geographic location and radius. The collection reaches 100GB with 10min of vehicle travel (and images less than 16MB) Because we need better resolution, we\u2019re hitting that 16MB limit now with just the image sizes. I understand the issue is a limit in BSON and there\u2019s another extension, GridFS, to store large BLOBs by writing them directly to the filesystem in chunks. It\u2019s my opinion that this makes the database, software, and filesystem more complex to manage, unless I\u2019m missing something.The reason we were sold on MongoDB was it\u2019s performance, nosql, and geospatial indexes. We\u2019re starting questioning the true performance after using MongoDB for 4 years. Each write to the collection, with just one spherical index, takes .5s on an i9, 64GB ram, with a Samsung 970EVO ssd. Granted, this isn\u2019t the fastest machine out there, but we\u2019re limited to what we can fit and power on an electric vehicle. What we\u2019re learning about database systems, like Cassandra, is they\u2019re faster and have document size limits (including BLOBs) of 2GB. I\u2019d really hate to rewrite my data abstraction layer.Also, the bsoncxx and mongocxx API documentation is really lacking and needs updating. It\u2019s mostly built with doxygen, with very few descriptive comments and few if any code examples. I had to read the source code to figure out writing and reading binary. It took me way longer to figure out how to write binary than was necessary. Here\u2019s an example of the only official documentation I could find on it.\nI don\u2019t know how anyone could get this from that documentation:\nCode: bsoncxx::types::b_binary b_blob \n { \n bsoncxx::binary_sub_type::k_binary,\n sizeof your_array_or_object,\n reinterpret_cast(&your_array_or_object)\n };\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Cannot connect to MongoDB on localhost using JDBC and tags: ['java', 'compass']"}, {"role": "user", "content": "Text:I\u2019m trying to use a simple Java program to connect to a MongoDB hosted on my Mac accessible by Compass using the authentication user and password I set up.However, in the JDBC code, I get the error 18 (authentication failure). I have no idea why. Same connection string as in Compass.My two dependencies in pom.xml are:The main method is utterly simple but failsI\u2019ve tried many variations on the connection string. None have worked.Here is the error I cannot get past: \u201cCommand failed with error 18 (AuthenticationFailed): \u2018Authentication failed.\u2019 on server localhost:27017. The full response is {\u201cok\u201d: 0.0, \u201cerrmsg\u201d: \u201cAuthentication failed.\u201d, \u201ccode\u201d: 18, \u201ccodeName\u201d: \u201cAuthenticationFailed\u201d}\u201dWould appreciate any suggestions on how to tackle this issue.Thanks\nCode: \n \n org.mongodb\n mongodb-driver-sync\n 4.6.0\n \n\n \n org.mongodb\n mongodb-jdbc\n 2.0.0\n \n \n try\n {\n Class.forName(\"com.mongodb.jdbc.MongoDriver\");\n \n Connection connection = DriverManager.getConnection(\n \"mongodb://corpus:passpass@localhost:27017/?authMechanism=DEFAULT&authSource=corpus_test\");\n\n.\n.\n.\n\n"}, {"role": "assistant", "content": "Text:Most likely your authSource is wrong.Try to simply remove it and the default admin will be used.It it sti\u013al does not work share the user data.\nCode:"}, {"role": "user", "content": "Text:I tried to remove that auth string, but it doesn\u2019t make any difference.Is JDBC a good way to work with MongoDB? I\u2019m really having trouble using the standard Mongo API and even getting a basic JDBC example to work. Also, can\u2019t find any books that contain JDBC for Mongo code. Stuff online is either out of date or just snippets with no complete examples. Difficult to get started\u2026Here\u2019s my revised connection code:\nCode: Class.forName(\"com.mongodb.jdbc.MongoDriver\");\n\n String url = \"jdbc:mongodb://localhost:27017\";\n Properties properties = new Properties();\n properties.put(\"database\", \"corpus_test\");\n properties.put(\"user\", \"corpus\");\n properties.put(\"password\", \"the_password\");\n\n Connection connection = DriverManager.getConnection(url, properties);\n\nCaused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {\"ok\": 0.0, \"errmsg\": \"Authentication failed.\", \"code\": 18, \"codeName\": \"AuthenticationFailed\"}\n\tat com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175)\n\tat com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:302)\n\tat com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:258)\n\tat com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)\n\tat com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)\n\tat com.mongodb.internal.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:158)\n\tat com.mongodb.internal.connection.SaslAuthenticator.access$100(SaslAuthenticator.java:40)\n\tat com.mongodb.internal.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:54)\n\t... 30 more\n"}, {"role": "assistant", "content": "Text:I do not use JDBC as I avoid abstraction layers.But Authentication Error means wrong user name, wrong password or wrong authentication database.It it sti\u013al does not work share the user data.\nCode:"}, {"role": "user", "content": "Text:The problem could be that there is no user created in the corpus_test database.In the admin database, I see this:\ndbdata1176\u00d71116 154 KB\nDoes this help?Thanks,\nCode:"}, {"role": "user", "content": "Text:See my posting (sorry, was posting when you wrote your reply) I added. I can connect, using Compass using these credentials.\nCompas Auth Works1502\u00d71298 152 KB\nWhen I click \u201cConnect\u201d, it connects with no problems.(The actual password is \u201cpasspass\u201d for testing.)Does this help?Thanks,\nCode:"}, {"role": "assistant", "content": "Text:The only thing I can say is that your JDBC abstraction layer is your obstruction layer because it does not generates the appropriate URI using the properties you set.I would first create my user in the admin database rather than corpus_test. Hopefully JDBC can use the default authentication database correctly. I suspect that the property database is not to specify the authSource. May be there is another one for that purpose.Hopefully, the driver uses user and password correctly, but you could put them yourself in the URL and not setting the properties.\nCode:"}, {"role": "user", "content": "Text:If you check the screenshot I posted above, you see that I did, in fact, create the user in the corpus_test database. Other than that, I have no idea what to try. I\u2019ve used every variation on the JDBC string I can think of.If I try something simple like:I get:java.sql.SQLException: There are issues with your connection settings : Mandatory property \u2018database\u2019 is missing.But, adding the \u201cdatabase\u201d as a property to the other JDBC connection attempt didn\u2019t work either.Thanks,\nCode: Connection connection = DriverManager.getConnection(\n \"jdbc:mongodb://localhost:27017/corpus_test\");\n"}, {"role": "user", "content": "Text: \u2192 Oops, sorry I meant the user was created in the admin database.See screenshot above.\nCode:"}, {"role": "assistant", "content": "Text:the user was created in the admin database.Apparently not, the evidences say otherwise, as the _id is corpus_test.corpus and you can conncect in Compass with authSource corpus_test.When publishing code or documents please do so in text rather than screenshot. It helps replying as we can cut-n-paste rather than typing.\nCode:"}, {"role": "user", "content": "Text:OK, you\u2019ve lost me. Here\u2019s the text version of the screenshot you requested. I tried to create the user in the corpus_test database, but it shows up here:If I go to the corpus_test database and try to create the user there, I get an incomprehensible message:\u2018switched to db corpus_test\u2019\ndb.createUser(\n{\nuser: \u201ccorpus\u201d,\npwd: \u201cpasspass\u201d,\nroles: [ { role: \u201creadWrite\u201d, db: \u201ccorpus_test\u201d }]}Error: clone(t={}){const r=t.loc||{};return e({loc:new Position(\"line\"in r?r.line:this.loc.line,\"column\"in r?r.column:\u2026\u2026)} could not be cloned.\nat Object.serialize (v8.js:256:7)\nat u (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:593159)\nat postMessage (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:593767)\nat i (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:598575)\nCode:use admin\n'switched to db admin'\ndb.system.users.find()\n{ _id: 'corpus_test.corpus',\n userId: UUID(\"3732b335-8734-4c15-b2f8-db2b2f0abb41\"),\n user: 'corpus',\n **db: 'corpus_test',**\n credentials:\n { 'SCRAM-SHA-1':\n { iterationCount: 10000,\n salt: '9yIjqaRMSG3umZbPXkvCEw==',\n storedKey: 'meLH8bvOfPXA1LjcjCEX4Lt/Ecw=',\n serverKey: 'k9dBvlJYm24BzAGX8s4Ugk30fwM=' },\n 'SCRAM-SHA-256':\n { iterationCount: 15000,\n salt: 'vWw3BFDN88idZqGnnZYNDLFq4Y03Y1GUe4hU+A==',\n storedKey: 'b1HixboG/j34sPbvl5+mfFHsQofCHM1vH/XfQZ1XXrM=',\n serverKey: 'J1dRZvofxEzX81Y1SlfI8eQQcjKrniDvSwiQ2uUfrjw=' } },\n roles: [ { role: 'readWrite', db: 'corpus_test' } ] }\n"}, {"role": "assistant", "content": "Text:Hi @c51a1608bd6dd1713da7ee458e75803First of all, I\u2019m not an expert in Java nor JDBC but I\u2019ll try to answer your question. Is this the JDBC driver you\u2019re using? GitHub - mongodb/mongo-jdbc-driver: JDBC Driver for MongoDB Atlas SQL interfaceIf yes, I think that driver is meant for connecting to a specific setup in Atlas and not to locally deployed instances, as mentioned in the Readme file there:The MongoDB Atlas SQL JDBC Driver provides SQL connectivity to MongoDB Atlas for client applications developed in Java.\nSee the Atlas SQL Documentation for more information.This is the diagram taken from the linked page https://www.mongodb.com/docs/atlas/data-federation/query/query-with-sql/\nimage1710\u00d7536 70.6 KB\nSo in the diagram, there\u2019s Atlas \u2192 Atlas SQL Interface \u2192 JDBC driverIn my limited knowledge, JDBC is a method for Java to connect to SQL/tabular databases. MongoDB is definitely not an SQL database. If you\u2019re looking to connect to MongoDB from Java, I think you\u2019re looking for the MongoBD Java driver, along with the free MongoDB University course M220J MongoDB for Java DevelopersBest regards\nKevin\nCode:"}, {"role": "assistant", "content": "Text:create the user in the corpus_test databaseYou did indeed created it in the corpus_test. This we know for sure as you could connect with Compass using corpus_test as authenticatin source. It is possible thzt JDBC driver cannot use an authenticaton source other than admin. So you should notgo to the corpus_test database and try to create the user therebecause you already created there and it does not work with JDBC. You have to create it in the admin database.\nCode:"}, {"role": "user", "content": "Text:This is very confusing. I did create the login in the admin database, but that login (user) refers to the corpus_test database. Trying to create the login in the corpus_test database throws that error I posted above:\nCode:Error: clone(t={}){const r=t.loc||{};return e({loc:new Position(\"line\"in r?r.line:this.loc.line,\"column\"in r?r.column:\u2026\u2026)} could not be cloned.\nat Object.serialize (v8.js:256:7)\nat u (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:593159)\nat postMessage (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:593767)\nat i (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:598575)\n"}, {"role": "assistant", "content": "Text:What is confusing is that I wrote many times that the user has NOT been created in the admin database:Apparently not, the evidences say otherwise, as the _id is corpus_test.corpus and you can conncect in Compass with authSource corpus_testYou did indeed created it in the corpus_test.I also wrote:You have to create it in the admin database.but you try to create it again in corpus_test.\nCode:"}, {"role": "user", "content": "Text:Doing a \u201cdb.system.users.find()\u201d in the corpus_test database shows no users. Nothing displays.If I try to create a user there, I get the errors I posted above.If I go to the admin database, db.system.users.find() shows the corpus_test user.If that is not correct, what database and what create user command should I use?Thanks,\nCode:"}, {"role": "assistant", "content": "Text:if these two does not work,\nCode:\"mongodb://corpus:passpass@localhost:27000/corpus_test?authMechanism=DEFAULT&authSource=corpus_test\"corpus_testtest\"mongodb://corpus:passpass@localhost:27000/corpus_test?authMechanism=DEFAULT&authSource=admin\"corpusadminsecurity.authorization: \"enabled\"/\"disabled\"admincorpusadmincorpus_testdb.dropUser(\"corpus\")"}, {"role": "user", "content": "Text:I\u2019m able to log in with no problems in Compass using authentication. Thanks.\nCode:"}, {"role": "assistant", "content": "Text:my bad \u2026 forgot the mongsh part while copy-pasting. remove it and use the rest of the string as your URL. I will edit my above post. the point is to have /corpus_test after the host name.the rest of those I suggested are because of the error you get for trying to add user to corpus_test db.\nCode:mongsh/corpus_testcorpus_test"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Help mongod command not working in M1 Mac and tags: []"}, {"role": "user", "content": "Text:Hello I have installed Mongo DB in M1 Mac as mentioned in the docs Install MongoDB Community Edition on macOS \u2014 MongoDB Manual\nBut when I try to run mongod command it gives me these errors.\nCode:{\"t\":{\"$date\":\"2022-01-01T16:13:21.271+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23285, \"ctx\":\"-\",\"msg\":\"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.272+05:30\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915701, \"ctx\":\"-\",\"msg\":\"Initialized wire specification\",\"attr\":{\"spec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":13},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":13},\"outgoing\":{\"minWireVersion\":0,\"maxWireVersion\":13},\"isInternalClient\":true}}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.275+05:30\"},\"s\":\"W\", \"c\":\"ASIO\", \"id\":22601, \"ctx\":\"main\",\"msg\":\"No TransportLayer configured during NetworkInterface startup\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.275+05:30\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4648602, \"ctx\":\"main\",\"msg\":\"Implicit TCP FastOpen in use.\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"W\", \"c\":\"ASIO\", \"id\":22601, \"ctx\":\"main\",\"msg\":\"No TransportLayer configured during NetworkInterface startup\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationDonorService\",\"ns\":\"config.tenantMigrationDonors\"}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"ns\":\"config.tenantMigrationRecipients\"}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"main\",\"msg\":\"Multi threading initialized\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":8149,\"port\":27017,\"dbPath\":\"/data/db\",\"architecture\":\"64-bit\",\"host\":\"Sais-MacBook-Pro.local\"}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"5.0.4\",\"gitVersion\":\"62a84ede3cc9a334e8bc82160714df71e7d3a29e\",\"modules\":[],\"allocator\":\"system\",\"environment\":{\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Mac OS X\",\"version\":\"21.2.0\"}}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.276+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{}}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.279+05:30\"},\"s\":\"E\", \"c\":\"CONTROL\", \"id\":20568, \"ctx\":\"initandlisten\",\"msg\":\"Error setting up listener\",\"attr\":{\"error\":{\"code\":9001,\"codeName\":\"SocketException\",\"errmsg\":\"Address already in use\"}}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.279+05:30\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784900, \"ctx\":\"initandlisten\",\"msg\":\"Stepping down the ReplicationCoordinator for shutdown\",\"attr\":{\"waitTimeMillis\":15000}}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.280+05:30\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784901, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the MirrorMaestro\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.280+05:30\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":4784902, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the WaitForMajorityService\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.280+05:30\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4784905, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the global connection pool\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.280+05:30\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4784918, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the ReplicaSetMonitor\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.280+05:30\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":4784921, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the MigrationUtilExecutor\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"ASIO\", \"id\":22582, \"ctx\":\"MigrationUtil-TaskExecutor\",\"msg\":\"Killing all outstanding egress activity.\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784923, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the ServiceEntryPoint\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784925, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down free monitoring\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784927, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the HealthLog\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784928, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the TTL monitor\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784929, \"ctx\":\"initandlisten\",\"msg\":\"Acquiring the global lock for shutdown\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"-\", \"id\":4784931, \"ctx\":\"initandlisten\",\"msg\":\"Dropping the scope cache for shutdown\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"FTDC\", \"id\":4784926, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down full-time data capture\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20565, \"ctx\":\"initandlisten\",\"msg\":\"Now exiting\"}\n{\"t\":{\"$date\":\"2022-01-01T16:13:21.281+05:30\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23138, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down\",\"attr\":{\"exitCode\":48}}\n"}, {"role": "assistant", "content": "Text:msg\":\"Error setting up listener\",\"attr\":{\"error\":{\"code\":9001,\"codeName\":\"SocketException\",\"errmsg\":\"Address already in use\"}}}Do you have another mongod already running?\nCode:msg\":\"Error setting up listener\",\"attr\":{\"error\":{\"code\":9001,\"codeName\":\"SocketException\",\"errmsg\":\"Address already in use\"}}}"}, {"role": "user", "content": "Text:I\u2019m not sure how can I check it?\nCode:"}, {"role": "assistant", "content": "Text:As per manual it is recommended to start mongod as serviceIf you have run brew services start there is no need to start mongod manually.Just issue mongo to connect to your instancecheck brew services list\nCode:"}, {"role": "assistant", "content": "Text:I\u2019m not sure how can I check it?With the shell commands\nCode:ps -aef | grep [m]ongod\nss -tlnp\n"}, {"role": "assistant", "content": "Text:is your issue resolved?? i\u2019m facing the same issue can you help me\u2026!\nCode:"}, {"role": "assistant", "content": "Text:Same issue means error 48?\nPlease show a screenshot or error logs\nAre you trying to start a mongod when there is already a mongod up and running?\nYou can check with commands given in previous\npost above\nCode:"}, {"role": "assistant", "content": "Text:i used mongo to connect instance now its working fine\u2026 but i\u2019m getting an error can you help me outcode: db.second.insertone({_id:1,name:\u201chero\u201d})\nerreor : uncaught exception: TypeError: db.second.insertone is not a function :\nCode:"}, {"role": "assistant", "content": "Text:my bad insert\"O\"ne. wrong spell, btw how can i connect u through social media\u2026?\nCode:"}, {"role": "assistant", "content": "Text:I also facing same issue.I\u2019m totally new to mongodb and has no knowledge about it at all.can anybody please help me\u2026\nthis is the error when i run mongod\nScreenshot 2022-06-24 at 11.58.57 AM1920\u00d7447 165 KB\n\nCode:"}, {"role": "assistant", "content": "Text:Check if your mongod is already up as service\nJust issue mongo and see if you can connect\nAlso check ps -ef | mongod if any mongod is up started manually\nAlso check permissions on that TMP .sock file\nCode:"}, {"role": "assistant", "content": "Text:can you explain it in a simpler manner\nCode:"}, {"role": "assistant", "content": "Text:Show us output of\nps -ef|grep mongod and\nls -lrt /tmp/mongod-27017.sock\nCode:"}, {"role": "assistant", "content": "Text:s -lrt /tmp/mongod-27017.sockThis is the response i am getting\n\nimage2734\u00d7194 68.3 KB\n\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: How can I do a LEFT OUTER JOIN in mongodb? and tags: ['aggregation', 'queries']"}, {"role": "user", "content": "Text:I have two collections:Collection 1:\nmail | value\na 2\nb 3\nc 4Collection 2:mail | value\na 2\nc 4Desired result:\nmail | value\nb 3How can I do this with the aggregation pipeline? Any help would be appreciated, I am just a begginer and I tried myself but with no success\u2026\nCode:"}, {"role": "assistant", "content": "Text:Hi @A_ML, and welcome to the MongoDB Community forums!In MongoDB the $lookuup operator does a left outer join of two collections.This will give results similar to the following based on your example:However it looks you want only those documents that exist in the left side and not the right side. You can add a $match to the above to return only where the joined field is an empty array (i.e. no matched document on the right side:Which returns:From there you can do what you need with the documents that remain in the pipeline.Note that this works just fine with the very small sample data, but you will want to test with larger amounts of production style data and make sure to filter out any unneeded documents before performing the lookup and make sure that the necessary indexes are in place.\nCode:$lookuupdb.coll1.aggregate([\n {\n $lookup: {\n from: \"coll2\",\n localField: \"mail\",\n foreignField: \"mail\",\n as: \"joined\"\n }\n }\n])\n[\n {\n _id: ObjectId(\"633219622627d7ac551adc7f\"),\n mail: 'a',\n value: 2,\n joined: [\n {\n _id: ObjectId(\"633219742627d7ac551adc82\"),\n mail: 'a',\n value: 2\n }\n ]\n },\n {\n _id: ObjectId(\"633219622627d7ac551adc80\"),\n mail: 'b',\n value: 3,\n joined: []\n },\n {\n _id: ObjectId(\"633219622627d7ac551adc81\"),\n mail: 'c',\n value: 4,\n joined: [\n {\n _id: ObjectId(\"633219742627d7ac551adc83\"),\n mail: 'c',\n value: 4\n }\n ]\n }\n]\n$matchjoineddb.coll1.aggregate([\n {\n $lookup: {\n from: \"coll2\",\n localField: \"mail\",\n foreignField: \"mail\",\n as: \"joined\"\n }\n },\n {\n $match: {\n joined: []\n }\n }\n])\n[\n {\n _id: ObjectId(\"633219622627d7ac551adc80\"),\n mail: 'b',\n value: 3,\n joined: []\n }\n]\n"}, {"role": "user", "content": "Text:Hi, thanks for your reply! I will take it into consideration. However, I would like to know how to do it taking two indexes at a time.\nFor example, not just looking at the column \u201cmail\u201d, but taking into account \u201cmail\u201d and \u201cvalues\u201d at the same time, since the same \u201cmail\u201d could have multiple records too. Is it possible with some kind of concatenation? In that case, is it possible to do it at runtime with a query?Thanks\nCode:{\n $match: {\n joined: []\n }\n }\n"}, {"role": "assistant", "content": "Text:The documentation covers multi field joins as well. You would use a form of the $lookup similar to the following:Hopefully the updated makes sense. Basically you create variables from the left collection fields to be used later in the pipeline. The pipeline then does the join (and could do other things as well if needed). Finally outside of the $lookup, you have you match to return only the documents that are not in the right collection.\nCode:$lookupdb.coll1.aggregate([{\n $lookup: {\n from: \"coll2\",\n let: {\n coll1_mail: \"$mail\",\n coll1_value: \"$value\"\n },\n pipeline: [{\n $match: {\n $expr: {\n $and: {\n $eq: [\"$$coll1_mail\", \"$mail\"],\n $eq: [\"$$coll1_value\", \"$value\"]\n }\n }\n }\n }],\n as: \"joined\"\n }\n },\n {\n $match: {\n joined: []\n }\n }\n])\n$lookup"}, {"role": "user", "content": "Text:Thanks for your help. Great explanation\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: MongoServerSelectionError: getaddrinfo ENOTFOUND and tags: ['node-js', 'connecting']"}, {"role": "user", "content": "Text:I followed the article you wrote but I\u2019m getting this error message .MongoServerSelectionError: getaddrinfo ENOTFOUND\nCode:"}, {"role": "assistant", "content": "Text:Welcome to the MongoDB community @Penuel_Nwaneri !MongoServerSelectionError: getaddrinfo ENOTFOUNDThe getaddrinfo ENOTFOUND error indicates that the hostname you have provided for your MongoDB deployment cannot be resolved by the client you are using.I would double-check the details in your connection string and try to ping that hostname from the command line to verify the name can be resolved to an IP address.If you are still having trouble connecting, please share some more details including:where your cluster is deployed (self-hosted, MongoDB Atlas, other \u2026)O/S version you are connecting fromconfirmation that the ping command is able to resolve the hostname for your MongoDB deployment to an IP addressIf this is a newly created deployment and DNS hostname, there may be a delay before the DNS information propagates through to your local DNS resolver. You may want to try changing your DNS servers to one of the public DNS services like Google Public DNS or Cloudflare public DNS.Regards,\nStennie\nCode:getaddrinfo ENOTFOUNDpingping"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Unable to start mongo instance on Mac OS Monterrey 12.6 using homebrew and tags: ['server', 'installation']"}, {"role": "user", "content": "Text:I have installed mongodb with homebrew following the guidelines here, but for some reason I cannot start my mongo instance I get the following error when running brew services run mongodb-communitybefore I didn\u2019t have that error, but some type of update happened that I can no longer run my mongo instancemongo logs inside /usr/local/var/log/mongodb\nCode:brew services run mongodb-communityBootstrap failed: 5: Input/output error\nTry re-running the command as root for richer errors.\nError: Failure while executing; `/bin/launchctl bootstrap gui/501 /usr/local/opt/mongodb-community/homebrew.mxcl.mongodb-community.plist` exited with 5.\n/usr/local/var/log/mongodb{\"t\":{\"$date\":\"2022-09-13T17:27:48.638+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20698, \"ctx\":\"-\",\"msg\":\"***** SERVER RESTARTED *****\"}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.643+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915701, \"ctx\":\"-\",\"msg\":\"Initialized wire specification\",\"attr\":{\"spec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"outgoing\":{\"minWireVersion\":6,\"maxWireVersion\":17},\"isInternalClient\":true}}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.648+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23285, \"ctx\":\"main\",\"msg\":\"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'\"}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.666+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4648602, \"ctx\":\"main\",\"msg\":\"Implicit TCP FastOpen in use.\"}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationDonorService\",\"namespace\":\"config.tenantMigrationDonors\"}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"namespace\":\"config.tenantMigrationRecipients\"}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"ShardSplitDonorService\",\"namespace\":\"config.tenantSplitDonors\"}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"main\",\"msg\":\"Multi threading initialized\"}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":21736,\"port\":27017,\"dbPath\":\"/usr/local/var/mongodb\",\"architecture\":\"64-bit\",\"host\":\"DSs-MacBook-Pro.local\"}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"6.0.1\",\"gitVersion\":\"32f0f9c88dc44a2c8073a5bd47cf779d4bfdee6b\",\"modules\":[],\"allocator\":\"system\",\"environment\":{\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Mac OS X\",\"version\":\"21.6.0\"}}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.673+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{\"config\":\"/usr/local/etc/mongod.conf\",\"net\":{\"bindIp\":\"127.0.0.1\"},\"storage\":{\"dbPath\":\"/usr/local/var/mongodb\"},\"systemLog\":{\"destination\":\"file\",\"logAppend\":true,\"path\":\"/usr/local/var/log/mongodb/mongo.log\"}}}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.674+02:00\"},\"s\":\"E\", \"c\":\"NETWORK\", \"id\":23024, \"ctx\":\"initandlisten\",\"msg\":\"Failed to unlink socket file\",\"attr\":{\"path\":\"/tmp/mongodb-27017.sock\",\"error\":\"Permission denied\"}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.674+02:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23091, \"ctx\":\"initandlisten\",\"msg\":\"Fatal assertion\",\"attr\":{\"msgid\":40486,\"file\":\"src/mongo/transport/transport_layer_asio.cpp\",\"line\":1120}}\n{\"t\":{\"$date\":\"2022-09-13T17:27:48.674+02:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23092, \"ctx\":\"initandlisten\",\"msg\":\"\\n\\n***aborting after fassert() failure\\n\\n\"}\n"}, {"role": "assistant", "content": "Text:It says permission denied on that TMP file\nCheck ownership of this file\nls -lrt /tmp/mongodb-27017.sock\nCheck if you have any mongod running\nps -ef|grep mongod or try mongo/mongosh depending on your shell\nIf you can connect means mongod is up\nLooks like you brought up mongod as root\nIf TMP file is owned by root shutdown all mongods and remove that TMP.sock file and start your service again\nCode:"}, {"role": "assistant", "content": "Text:In addition to the advice that Ramachandra provided, if mongod had been started by root it\u2019s highly probable that the data and log files/directories are also owned by the root user. You will need to check those as well and change the ownership of those before mongod will run as your normal user.\nCode:mongodrootrootmongod"}, {"role": "user", "content": "Text:ls -lrt /tmp/mongodb-27017.sockThanks @Ramachandra_Tummala and @Doug_Duncan for the reply I\u2019m a frontend developer so I don\u2019t have too much experience with this sort of thing, so I might need your help a bit more.When I do ls -lrt /tmp/mongodb-27017.sockI get the following srwx------ 1 root wheel 0 Sep 15 11:37 /tmp/mongodb-27017.sock\nso I guess the owner of this is rootI deleted the mongodb-27017.sock and restarted the service (I have stopped all services before this)When I check the ownership again, now I get srwx------ 1 ds wheel 0 Sep 15 11:48 /tmp/mongodb-27017.sock (ds == my user)But I\u2019m still unable to start the mongo-community though.I get the following error:This is my mongod.conf I have the following insideAnd this are the permissions for `usr/local/var/\u2026\nCode:ls -lrt /tmp/mongodb-27017.socksrwx------ 1 root wheel 0 Sep 15 11:37 /tmp/mongodb-27017.sockrootmongodb-27017.socksrwx------ 1 ds wheel 0 Sep 15 11:48 /tmp/mongodb-27017.sock{\"t\":{\"$date\":\"2022-09-15T11:48:25.621+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20698, \"ctx\":\"-\",\"msg\":\"***** SERVER RESTARTED *****\"}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.627+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915701, \"ctx\":\"-\",\"msg\":\"Initialized wire specification\",\"attr\":{\"spec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"outgoing\":{\"minWireVersion\":6,\"maxWireVersion\":17},\"isInternalClient\":true}}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.639+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23285, \"ctx\":\"main\",\"msg\":\"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'\"}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.639+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4648602, \"ctx\":\"main\",\"msg\":\"Implicit TCP FastOpen in use.\"}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.643+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationDonorService\",\"namespace\":\"config.tenantMigrationDonors\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.643+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"namespace\":\"config.tenantMigrationRecipients\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.643+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"ShardSplitDonorService\",\"namespace\":\"config.tenantSplitDonors\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.643+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"main\",\"msg\":\"Multi threading initialized\"}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.643+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":4834,\"port\":27017,\"dbPath\":\"/usr/local/var/mongodb\",\"architecture\":\"64-bit\",\"host\":\"DSs-MacBook-Pro.local\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.644+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"6.0.1\",\"gitVersion\":\"32f0f9c88dc44a2c8073a5bd47cf779d4bfdee6b\",\"modules\":[],\"allocator\":\"system\",\"environment\":{\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.644+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Mac OS X\",\"version\":\"21.6.0\"}}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.644+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{\"config\":\"/usr/local/etc/mongod.conf\",\"net\":{\"bindIp\":\"127.0.0.1\"},\"storage\":{\"dbPath\":\"/usr/local/var/mongodb\"},\"systemLog\":{\"destination\":\"file\",\"logAppend\":true,\"path\":\"/usr/local/var/log/mongodb/mongo.log\"}}}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.645+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":5693100, \"ctx\":\"initandlisten\",\"msg\":\"Asio socket.set_option failed with std::system_error\",\"attr\":{\"note\":\"acceptor TCP fast open\",\"option\":{\"level\":6,\"name\":261,\"data\":\"00 04 00 00\"},\"error\":{\"what\":\"set_option: Invalid argument\",\"message\":\"Invalid argument\",\"category\":\"asio.system\",\"value\":22}}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.645+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22270, \"ctx\":\"initandlisten\",\"msg\":\"Storage engine to use detected by data files\",\"attr\":{\"dbpath\":\"/usr/local/var/mongodb\",\"storageEngine\":\"wiredTiger\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:25.646+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22315, \"ctx\":\"initandlisten\",\"msg\":\"Opening WiredTiger\",\"attr\":{\"config\":\"create,cache_size=3584M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.070+02:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1663235306:69670][4834:0x11c7a5600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /usr/local/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1663235306:72132][4834:0x11c7a5600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /usr/local/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1663235306:72436][4834:0x11c7a5600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /usr/local/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"W\", \"c\":\"STORAGE\", \"id\":22347, \"ctx\":\"initandlisten\",\"msg\":\"Failed to start up WiredTiger under any compatibility version. This may be due to an unsupported upgrade or downgrade.\"}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"F\", \"c\":\"STORAGE\", \"id\":28595, \"ctx\":\"initandlisten\",\"msg\":\"Terminating.\",\"attr\":{\"reason\":\"13: Permission denied\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23091, \"ctx\":\"initandlisten\",\"msg\":\"Fatal assertion\",\"attr\":{\"msgid\":28595,\"file\":\"src/mongo/db/storage/wiredtiger/wiredtiger_kv_engine.cpp\",\"line\":702}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"F\", \"c\":\"ASSERT\", \"id\":23092, \"ctx\":\"initandlisten\",\"msg\":\"\\n\\n***aborting after fassert() failure\\n\\n\"}\n\nmongod.confsystemLog:\n destination: file\n path: /usr/local/var/log/mongodb/mongo.log\n logAppend: true\nstorage:\n dbPath: /usr/local/var/mongodb\nnet:\n bindIp: 127.0.0.1\ndrwxrwxr-x 7 ds admin 224B Sep 13 14:13 .\ndrwxr-xr-x 18 root wheel 576B Sep 13 14:13 ..\ndrwxr-xr-x 3 ds admin 96B Nov 5 2020 cache\ndrwxrwxr-x 4 ds admin 128B Feb 24 2020 homebrew\ndrwxr-xr-x 3 ds admin 96B Nov 16 2020 log\ndrwxr-xr-x 136 ds admin 4.3K Sep 15 11:37 mongodb\ndrwxr-xr-x 3 ds admin 96B Sep 13 14:13 run\n"}, {"role": "assistant", "content": "Text:The above lines show that you\u2019re still having permission problems. This time on files in the data directory (/uar/local/var/mongodb/). My guess is that the files under this path are owned by the root user as well. To check run ls -alh /usr/local/var/mongodb/*. If things are owned by the root user, then you would either need to delete them or change the ownership of the files.I\u2019m assuming you installed via brew and then started the mongod as the root user and that\u2019s why all the permissions are messed up. You should never run (almost) any service as the root user, and only then if you understand, and are willing to accept, the risks involved with doing so.\nCode:{\"t\":{\"$date\":\"2022-09-15T11:48:26.070+02:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1663235306:69670][4834:0x11c7a5600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /usr/local/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1663235306:72132][4834:0x11c7a5600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /usr/local/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n{\"t\":{\"$date\":\"2022-09-15T11:48:26.072+02:00\"},\"s\":\"E\", \"c\":\"WT\", \"id\":22435, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger error message\",\"attr\":{\"error\":13,\"message\":\"[1663235306:72436][4834:0x11c7a5600], wiredtiger_open: [WT_VERB_DEFAULT][ERROR]: int __posix_open_file(WT_FILE_SYSTEM *, WT_SESSION *, const char *, WT_FS_OPEN_FILE_TYPE, uint32_t, WT_FILE_HANDLE **), 805: /usr/local/var/mongodb/WiredTiger.turtle: handle-open: open: Permission denied\"}}\n/uar/local/var/mongodb/rootls -alh /usr/local/var/mongodb/*rootbrewmongodrootroot"}, {"role": "user", "content": "Text:ls -alh /usr/local/var/mongodb/*When I run ls -alh /usr/local/var/mongodb/*I get the following:So I have 4 files owned by rootHow can I change the permissions back to my user ?I did installed mongod with brew but don\u2019t remmeber running anything as root mosty likely I types something by mistake without knowing\nCode:ls -alh /usr/local/var/mongodb/*-rw------- 1 ds admin 47B Nov 16 2020 /usr/local/var/mongodb/WiredTiger\n-rw------- 1 ds admin 21B Nov 16 2020 /usr/local/var/mongodb/WiredTiger.lock\n-rw------- 1 root admin 1.3K Sep 15 11:37 /usr/local/var/mongodb/WiredTiger.turtle\n-rw------- 1 ds admin 424K Sep 15 11:37 /usr/local/var/mongodb/WiredTiger.wt\n-rw------- 1 ds admin 12K Sep 15 11:37 /usr/local/var/mongodb/WiredTigerHS.wt\n-rw------- 1 ds admin 44K Sep 15 11:37 /usr/local/var/mongodb/_mdb_catalog.wt\n-rw------- 1 ds admin 32K Sep 15 11:37 /usr/local/var/mongodb/collection-0--5484561422099317879.wt\n-rw------- 1 ds admin 4.0K Aug 16 17:50 /usr/local/var/mongodb/collection-0--8938186976542024012.wt\n-rw------- 1 ds admin 44K Aug 30 12:20 /usr/local/var/mongodb/collection-0-6646607318980365885.wt\n-rw------- 1 ds admin 36K Aug 4 10:27 /usr/local/var/mongodb/collection-0-828309438715058860.wt\n-rw------- 1 ds admin 4.0K Aug 16 17:50 /usr/local/var/mongodb/collection-1--8938186976542024012.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-177-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-178-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-179-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-180-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-185-997841842072881824.wt\n-rw------- 1 ds admin 36K Aug 31 13:35 /usr/local/var/mongodb/collection-186--6760981820974790918.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-186-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-187-997841842072881824.wt\n-rw------- 1 ds admin 36K Aug 31 13:46 /usr/local/var/mongodb/collection-188--6760981820974790918.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-188-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-193-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/collection-194-997841842072881824.wt\n-rw------- 1 ds admin 52K Aug 4 10:28 /usr/local/var/mongodb/collection-2--5484561422099317879.wt\n-rw------- 1 ds admin 4.0K Aug 16 17:50 /usr/local/var/mongodb/collection-2--8938186976542024012.wt\n-rw------- 1 ds admin 60K Aug 31 13:46 /usr/local/var/mongodb/collection-2-236702729281165765.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-2-7829836989468010820.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-237--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-238--3421962067213660962.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-24-4461830987773809247.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-240--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-241--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-243--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-244--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-245--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-246--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-247--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-248--3421962067213660962.wt\n-rw------- 1 ds admin 36K Aug 4 10:27 /usr/local/var/mongodb/collection-3--4968984876227865773.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-30--7761360505503786663.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-32--7761360505503786663.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-34--7761360505503786663.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-3771--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-3772--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jun 15 15:44 /usr/local/var/mongodb/collection-3778--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jun 15 15:44 /usr/local/var/mongodb/collection-3779--3383466982208816242.wt\n-rw------- 1 ds admin 12K Aug 4 10:27 /usr/local/var/mongodb/collection-3798--3383466982208816242.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-3800--3383466982208816242.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-3802--3383466982208816242.wt\n-rw------- 1 ds admin 12K Sep 1 14:39 /usr/local/var/mongodb/collection-4--5484561422099317879.wt\n-rw------- 1 ds admin 12K Aug 4 10:27 /usr/local/var/mongodb/collection-4-8395434167465204535.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-442-285365223316158836.wt\n-rw------- 1 ds admin 3.3M Aug 4 10:27 /usr/local/var/mongodb/collection-454--3592809970845984021.wt\n-rw------- 1 ds admin 3.3M Aug 4 10:27 /usr/local/var/mongodb/collection-456--3592809970845984021.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/collection-6-8395434167465204535.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-761-6865724622955516652.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-765-6865724622955516652.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-767-6865724622955516652.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/collection-769-6865724622955516652.wt\n-rw------- 1 ds admin 44K Aug 31 13:46 /usr/local/var/mongodb/collection-8-7829836989468010820.wt\n-rw------- 1 ds admin 7.2M Aug 4 10:27 /usr/local/var/mongodb/collection-80--7761360505503786663.wt\n-rw------- 1 ds admin 32K Sep 15 11:37 /usr/local/var/mongodb/index-1--5484561422099317879.wt\n-rw------- 1 ds admin 36K Aug 30 12:20 /usr/local/var/mongodb/index-1-6646607318980365885.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-1-828309438715058860.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-10--4968984876227865773.wt\n-rw------- 1 ds admin 36K Aug 31 13:35 /usr/local/var/mongodb/index-118-6865724622955516652.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-181-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-182-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-183-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-184-997841842072881824.wt\n-rw------- 1 ds admin 36K Aug 31 13:35 /usr/local/var/mongodb/index-187--6760981820974790918.wt\n-rw------- 1 ds admin 36K Aug 31 13:46 /usr/local/var/mongodb/index-189--6760981820974790918.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-189-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-190-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-191-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-192-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-196-997841842072881824.wt\n-rw------- 1 ds admin 4.0K Jun 21 17:24 /usr/local/var/mongodb/index-197-997841842072881824.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-2-828309438715058860.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-239--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-242--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-249--3421962067213660962.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-25-4461830987773809247.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-250--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-251--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-252--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-253--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-254--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-255--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-256--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-257--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-258--3421962067213660962.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-259--3421962067213660962.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-26-4461830987773809247.wt\n-rw------- 1 ds admin 36K Aug 4 10:28 /usr/local/var/mongodb/index-3--5484561422099317879.wt\n-rw------- 1 ds admin 44K Aug 31 13:46 /usr/local/var/mongodb/index-3-236702729281165765.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-3-7829836989468010820.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-31--7761360505503786663.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-33--7761360505503786663.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-35--7761360505503786663.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-3773--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-3774--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-3775--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-3776--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-3777--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jun 15 15:44 /usr/local/var/mongodb/index-3780--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jun 15 15:44 /usr/local/var/mongodb/index-3781--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jun 15 15:44 /usr/local/var/mongodb/index-3782--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jun 15 15:44 /usr/local/var/mongodb/index-3783--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Jun 15 15:44 /usr/local/var/mongodb/index-3784--3383466982208816242.wt\n-rw------- 1 ds admin 12K Aug 4 10:27 /usr/local/var/mongodb/index-3799--3383466982208816242.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-3801--3383466982208816242.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-3803--3383466982208816242.wt\n-rw------- 1 ds admin 4.0K Aug 16 17:50 /usr/local/var/mongodb/index-4--8938186976542024012.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-443-285365223316158836.wt\n-rw------- 1 ds admin 492K Aug 4 10:27 /usr/local/var/mongodb/index-455--3592809970845984021.wt\n-rw------- 1 ds admin 492K Aug 4 10:27 /usr/local/var/mongodb/index-457--3592809970845984021.wt\n-rw------- 1 ds admin 12K Sep 1 14:39 /usr/local/var/mongodb/index-5--5484561422099317879.wt\n-rw------- 1 ds admin 4.0K Aug 16 17:50 /usr/local/var/mongodb/index-5--8938186976542024012.wt\n-rw------- 1 ds admin 12K Aug 4 10:27 /usr/local/var/mongodb/index-5-8395434167465204535.wt\n-rw------- 1 ds admin 12K Sep 1 15:14 /usr/local/var/mongodb/index-6--5484561422099317879.wt\n-rw------- 1 ds admin 4.0K Aug 16 17:50 /usr/local/var/mongodb/index-6--8938186976542024012.wt\n-rw------- 1 ds admin 32K Aug 4 10:27 /usr/local/var/mongodb/index-7-8395434167465204535.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-762-6865724622955516652.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-766-6865724622955516652.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-768-6865724622955516652.wt\n-rw------- 1 ds admin 4.0K Jul 6 12:13 /usr/local/var/mongodb/index-770-6865724622955516652.wt\n-rw------- 1 ds admin 508K Aug 4 10:27 /usr/local/var/mongodb/index-81--7761360505503786663.wt\n-rw------- 1 ds admin 44K Aug 31 13:46 /usr/local/var/mongodb/index-9-7829836989468010820.wt\n-rw------- 1 ds admin 0B Sep 15 11:37 /usr/local/var/mongodb/mongod.lock\n-rw------- 1 ds admin 52K Sep 15 11:37 /usr/local/var/mongodb/sizeStorer.wt\n-rw------- 1 ds admin 114B Nov 16 2020 /usr/local/var/mongodb/storage.bson\n\n/usr/local/var/mongodb/diagnostic.data:\ntotal 400800\ndrwx------ 35 ds admin 1.1K Sep 1 15:14 .\ndrwxr-xr-x 136 ds admin 4.3K Sep 15 11:37 ..\n-rw------- 1 ds admin 8.2M Nov 29 2021 metrics.2021-11-18T11-49-09Z-00000\n-rw------- 1 ds admin 1.2M Nov 30 2021 metrics.2021-11-29T14-41-45Z-00000\n-rw------- 1 ds admin 10M Dec 14 2021 metrics.2021-11-30T14-16-00Z-00000\n-rw------- 1 ds admin 10M Jan 1 2022 metrics.2021-12-14T09-18-59Z-00000\n-rw------- 1 ds admin 10M Jan 15 2022 metrics.2022-01-01T16-09-07Z-00000\n-rw------- 1 ds admin 8.9M Jan 25 2022 metrics.2022-01-15T10-11-43Z-00000\n-rw------- 1 ds admin 3.4M Jan 31 2022 metrics.2022-01-25T16-09-27Z-00000\n-rw------- 1 ds admin 1.7M Feb 1 2022 metrics.2022-01-31T12-45-14Z-00000\n-rw------- 1 ds admin 10M Feb 13 2022 metrics.2022-02-01T13-04-03Z-00000\n-rw------- 1 ds admin 4.0M Feb 16 2022 metrics.2022-02-13T14-12-22Z-00000\n-rw------- 1 ds admin 1.1M Feb 17 2022 metrics.2022-02-16T18-39-49Z-00000\n-rw------- 1 ds admin 7.0M Feb 24 2022 metrics.2022-02-17T13-36-11Z-00000\n-rw------- 1 ds admin 10M Mar 7 2022 metrics.2022-02-24T12-53-15Z-00000\n-rw------- 1 ds admin 4.0M Mar 11 2022 metrics.2022-03-07T10-52-13Z-00000\n-rw------- 1 ds admin 10M Mar 25 08:58 metrics.2022-03-14T11-48-19Z-00000\n-rw------- 1 ds admin 1.2M Mar 28 10:00 metrics.2022-03-25T07-58-11Z-00000\n-rw------- 1 ds admin 10M Apr 7 12:57 metrics.2022-03-28T08-04-37Z-00000\n-rw------- 1 ds admin 10M Apr 16 11:41 metrics.2022-04-07T10-57-17Z-00000\n-rw------- 1 ds admin 10M Apr 26 09:42 metrics.2022-04-16T09-41-27Z-00000\n-rw------- 1 ds admin 8.7M May 5 13:05 metrics.2022-04-26T07-42-58Z-00000\n-rw------- 1 ds admin 90K May 5 13:31 metrics.2022-05-05T11-05-16Z-00000\n-rw------- 1 ds admin 1.8M May 8 22:06 metrics.2022-05-05T13-06-17Z-00000\n-rw------- 1 ds admin 10M May 19 19:38 metrics.2022-05-09T12-10-40Z-00000\n-rw------- 1 ds admin 10M Jun 15 13:19 metrics.2022-05-19T17-38-50Z-00000\n-rw------- 1 ds admin 158K Jun 15 15:44 metrics.2022-06-15T11-19-30Z-00000\n-rw------- 1 ds admin 5.2M Jun 21 17:24 metrics.2022-06-16T07-45-34Z-00000\n-rw------- 1 ds admin 7.8M Jul 6 12:13 metrics.2022-06-27T09-46-37Z-00000\n-rw------- 1 ds admin 13K Jul 6 12:14 metrics.2022-07-06T10-14-28Z-00000\n-rw------- 1 ds admin 909K Jul 19 10:16 metrics.2022-07-18T08-41-51Z-00000\n-rw------- 1 ds admin 10M Aug 22 21:04 metrics.2022-08-04T08-27-31Z-00000\n-rw------- 1 ds admin 10M Sep 1 11:53 metrics.2022-08-22T19-04-17Z-00000\n-rw------- 1 ds admin 449K Sep 1 15:13 metrics.2022-09-01T09-53-05Z-00000\n-rw------- 1 ds admin 10K Sep 1 15:14 metrics.interim\n\n/usr/local/var/mongodb/journal:\ntotal 24\ndrwx------ 5 ds admin 160B Sep 15 11:37 .\ndrwxr-xr-x 136 ds admin 4.3K Sep 15 11:37 ..\n-rw------- 1 root admin 100M Sep 15 11:37 WiredTigerLog.0000000048\n-rw------- 1 root admin 100M Sep 15 11:37 WiredTigerPreplog.0000000001\n-rw------- 1 root admin 100M Sep 15 11:37 WiredTigerPreplog.0000000002\nroot-rw------- 1 root admin 1.3K Sep 15 11:37 /usr/local/var/mongodb/WiredTiger.turtle\n-rw------- 1 root admin 100M Sep 15 11:37 WiredTigerLog.0000000048\n-rw------- 1 root admin 100M Sep 15 11:37 WiredTigerPreplog.0000000001\n-rw------- 1 root admin 100M Sep 15 11:37 WiredTigerPreplog.0000000002\nmongodbrewroot"}, {"role": "user", "content": "Text:@Doug_Duncan I guess I can change ownership of a filme with chown <$USER> ??\nCode:chown <$USER> "}, {"role": "assistant", "content": "Text:You would need to run the following commands:\nCode:sudo chown ds /usr/local/var/mongodb/WiredTiger.turtle\nsudo chown ds /usr/local/var/mongodb/journal/WiredTiger*\n"}, {"role": "user", "content": "Text:Ok this work, I changed all file permissions,Howeever still unable to run mongodthe logs tell me{\"t\":{\"$date\":\"2022-09-15T15:52:44.717+02:00\"},\"s\":\"F\", \"c\":\"CONTROL\", \"id\":20573, \"ctx\":\"initandlisten\",\"msg\":\"Wrong mongod version\",\"attr\":{\"error\":\"UPGRADE PROBLEM: Found an invalid featureCompatibilityVersion document (ERROR: Location4926900: Invalid featureCompatibilityVersion document in admin.system.version: { _id: \\\"featureCompatibilityVersion\\\", version: \\\"4.4\\\" }. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility. :: caused by :: Invalid feature compatibility version value, expected '5.0' or '5.3' or '6.0. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility.). If the current featureCompatibilityVersion is below 5.0, see the documentation on upgrading at https://docs.mongodb.com/master/release-notes/5.0/#upgrade-procedures.\"}}so don\u2019t know is that\u2019s still the cause or is the fact that when I try to run brew services list I still see mongodb-community error 15872 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist does this file also need to be owned by ds or root ?\nCode:mongod{\"t\":{\"$date\":\"2022-09-15T15:52:43.582+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20698, \"ctx\":\"-\",\"msg\":\"***** SERVER RESTARTED *****\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.601+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23285, \"ctx\":\"-\",\"msg\":\"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.601+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4915701, \"ctx\":\"-\",\"msg\":\"Initialized wire specification\",\"attr\":{\"spec\":{\"incomingExternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"incomingInternalClient\":{\"minWireVersion\":0,\"maxWireVersion\":17},\"outgoing\":{\"minWireVersion\":6,\"maxWireVersion\":17},\"isInternalClient\":true}}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.605+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4648602, \"ctx\":\"main\",\"msg\":\"Implicit TCP FastOpen in use.\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationDonorService\",\"namespace\":\"config.tenantMigrationDonors\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"TenantMigrationRecipientService\",\"namespace\":\"config.tenantMigrationRecipients\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":5123008, \"ctx\":\"main\",\"msg\":\"Successfully registered PrimaryOnlyService\",\"attr\":{\"service\":\"ShardSplitDonorService\",\"namespace\":\"config.tenantSplitDonors\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":5945603, \"ctx\":\"main\",\"msg\":\"Multi threading initialized\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4615611, \"ctx\":\"initandlisten\",\"msg\":\"MongoDB starting\",\"attr\":{\"pid\":16054,\"port\":27017,\"dbPath\":\"/usr/local/var/mongodb\",\"architecture\":\"64-bit\",\"host\":\"DSs-MacBook-Pro.local\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"6.0.1\",\"gitVersion\":\"32f0f9c88dc44a2c8073a5bd47cf779d4bfdee6b\",\"modules\":[],\"allocator\":\"system\",\"environment\":{\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":51765, \"ctx\":\"initandlisten\",\"msg\":\"Operating System\",\"attr\":{\"os\":{\"name\":\"Mac OS X\",\"version\":\"21.6.0\"}}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":21951, \"ctx\":\"initandlisten\",\"msg\":\"Options set by command line\",\"attr\":{\"options\":{\"config\":\"/usr/local/etc/mongod.conf\",\"net\":{\"bindIp\":\"127.0.0.1\"},\"storage\":{\"dbPath\":\"/usr/local/var/mongodb\"},\"systemLog\":{\"destination\":\"file\",\"logAppend\":true,\"path\":\"/usr/local/var/log/mongodb/mongo.log\"}}}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.615+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":5693100, \"ctx\":\"initandlisten\",\"msg\":\"Asio socket.set_option failed with std::system_error\",\"attr\":{\"note\":\"acceptor TCP fast open\",\"option\":{\"level\":6,\"name\":261,\"data\":\"00 04 00 00\"},\"error\":{\"what\":\"set_option: Invalid argument\",\"message\":\"Invalid argument\",\"category\":\"asio.system\",\"value\":22}}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.616+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22270, \"ctx\":\"initandlisten\",\"msg\":\"Storage engine to use detected by data files\",\"attr\":{\"dbpath\":\"/usr/local/var/mongodb\",\"storageEngine\":\"wiredTiger\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:43.617+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22315, \"ctx\":\"initandlisten\",\"msg\":\"Opening WiredTiger\",\"attr\":{\"config\":\"create,cache_size=3584M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,remove=true,path=journal,compressor=snappy),builtin_extension_config=(zstd=(compression_level=6)),file_manager=(close_idle_time=600,close_scan_interval=10,close_handle_minimum=2000),statistics_log=(wait=0),json_output=(error,message),verbose=[recovery_progress:1,checkpoint_progress:1,compact_progress:1,backup:0,checkpoint:0,compact:0,evict:0,history_store:0,recovery:0,rts:0,salvage:0,tiered:0,timestamp:0,transaction:0,verify:0,log:0],\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.627+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4795906, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger opened\",\"attr\":{\"durationMillis\":1010}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.628+02:00\"},\"s\":\"I\", \"c\":\"RECOVERY\", \"id\":23987, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger recoveryTimestamp\",\"attr\":{\"recoveryTimestamp\":{\"$timestamp\":{\"t\":0,\"i\":0}}}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.629+02:00\"},\"s\":\"I\", \"c\":\"WT\", \"id\":4366408, \"ctx\":\"initandlisten\",\"msg\":\"No table logging settings modifications are required for existing WiredTiger tables\",\"attr\":{\"loggingEnabled\":true}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.710+02:00\"},\"s\":\"W\", \"c\":\"CONTROL\", \"id\":22120, \"ctx\":\"initandlisten\",\"msg\":\"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted\",\"tags\":[\"startupWarnings\"]}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.717+02:00\"},\"s\":\"F\", \"c\":\"CONTROL\", \"id\":20573, \"ctx\":\"initandlisten\",\"msg\":\"Wrong mongod version\",\"attr\":{\"error\":\"UPGRADE PROBLEM: Found an invalid featureCompatibilityVersion document (ERROR: Location4926900: Invalid featureCompatibilityVersion document in admin.system.version: { _id: \\\"featureCompatibilityVersion\\\", version: \\\"4.4\\\" }. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility. :: caused by :: Invalid feature compatibility version value, expected '5.0' or '5.3' or '6.0. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility.). If the current featureCompatibilityVersion is below 5.0, see the documentation on upgrading at https://docs.mongodb.com/master/release-notes/5.0/#upgrade-procedures.\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.717+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784900, \"ctx\":\"initandlisten\",\"msg\":\"Stepping down the ReplicationCoordinator for shutdown\",\"attr\":{\"waitTimeMillis\":15000}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.718+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4794602, \"ctx\":\"initandlisten\",\"msg\":\"Attempting to enter quiesce mode\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.718+02:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":6371601, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the FLE Crud thread pool\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784901, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the MirrorMaestro\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":4784902, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the WaitForMajorityService\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":20562, \"ctx\":\"initandlisten\",\"msg\":\"Shutdown: going to close listening sockets\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4784905, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the global connection pool\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784906, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the FlowControlTicketholder\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":20520, \"ctx\":\"initandlisten\",\"msg\":\"Stopping further Flow Control ticket acquisitions.\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784908, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the PeriodicThreadToAbortExpiredTransactions\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784909, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the ReplicationCoordinator\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":4784910, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the ShardingInitializationMongoD\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784911, \"ctx\":\"initandlisten\",\"msg\":\"Enqueuing the ReplicationStateTransitionLock for shutdown\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4784912, \"ctx\":\"initandlisten\",\"msg\":\"Killing all operations for shutdown\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4695300, \"ctx\":\"initandlisten\",\"msg\":\"Interrupted all currently running operations\",\"attr\":{\"opsKilled\":3}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"TENANT_M\", \"id\":5093807, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down all TenantMigrationAccessBlockers on global shutdown\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784913, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down all open transactions\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"REPL\", \"id\":4784914, \"ctx\":\"initandlisten\",\"msg\":\"Acquiring the ReplicationStateTransitionLock for shutdown\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"INDEX\", \"id\":4784915, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the IndexBuildsCoordinator\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"NETWORK\", \"id\":4784918, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the ReplicaSetMonitor\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.719+02:00\"},\"s\":\"I\", \"c\":\"SHARDING\", \"id\":4784921, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the MigrationUtilExecutor\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.720+02:00\"},\"s\":\"I\", \"c\":\"ASIO\", \"id\":22582, \"ctx\":\"MigrationUtil-TaskExecutor\",\"msg\":\"Killing all outstanding egress activity.\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"COMMAND\", \"id\":4784923, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the ServiceEntryPoint\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784925, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down free monitoring\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784927, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the HealthLog\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784928, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the TTL monitor\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":6278511, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the Change Stream Expired Pre-images Remover\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784929, \"ctx\":\"initandlisten\",\"msg\":\"Acquiring the global lock for shutdown\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":4784930, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down the storage engine\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22320, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down journal flusher thread\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22321, \"ctx\":\"initandlisten\",\"msg\":\"Finished shutting down journal flusher thread\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22322, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down checkpoint thread\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22323, \"ctx\":\"initandlisten\",\"msg\":\"Finished shutting down checkpoint thread\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":20282, \"ctx\":\"initandlisten\",\"msg\":\"Deregistering all the collections\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22317, \"ctx\":\"initandlisten\",\"msg\":\"WiredTigerKVEngine shutting down\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22318, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down session sweeper thread\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22319, \"ctx\":\"initandlisten\",\"msg\":\"Finished shutting down session sweeper thread\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.721+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4795902, \"ctx\":\"initandlisten\",\"msg\":\"Closing WiredTiger\",\"attr\":{\"closeConfig\":\"leak_memory=true,\"}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.975+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":4795901, \"ctx\":\"initandlisten\",\"msg\":\"WiredTiger closed\",\"attr\":{\"durationMillis\":254}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.975+02:00\"},\"s\":\"I\", \"c\":\"STORAGE\", \"id\":22279, \"ctx\":\"initandlisten\",\"msg\":\"shutdown: removing fs lock...\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.976+02:00\"},\"s\":\"I\", \"c\":\"-\", \"id\":4784931, \"ctx\":\"initandlisten\",\"msg\":\"Dropping the scope cache for shutdown\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.976+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":20565, \"ctx\":\"initandlisten\",\"msg\":\"Now exiting\"}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.976+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23138, \"ctx\":\"initandlisten\",\"msg\":\"Shutting down\",\"attr\":{\"exitCode\":62}}\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.717+02:00\"},\"s\":\"F\", \"c\":\"CONTROL\", \"id\":20573, \"ctx\":\"initandlisten\",\"msg\":\"Wrong mongod version\",\"attr\":{\"error\":\"UPGRADE PROBLEM: Found an invalid featureCompatibilityVersion document (ERROR: Location4926900: Invalid featureCompatibilityVersion document in admin.system.version: { _id: \\\"featureCompatibilityVersion\\\", version: \\\"4.4\\\" }. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility. :: caused by :: Invalid feature compatibility version value, expected '5.0' or '5.3' or '6.0. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility.). If the current featureCompatibilityVersion is below 5.0, see the documentation on upgrading at https://docs.mongodb.com/master/release-notes/5.0/#upgrade-procedures.\"}}brew services listmongodb-community error 15872 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plistdsroot"}, {"role": "assistant", "content": "Text:You had an older version of MongoDB installed (4.4) that created the database files and you are now trying to run MongoDB 6.0.1 on your system. Below are the relevant log entries showing this:Do you need the data from the older version? If not you can go into /usr/local/var/mongodb and delete all the files/folders. Those should get recreated the next time you start the mongod process. If you need/want to keep the data, then you would need to install MongoDB 5.0.x to let the FeatureCompatabilityVersion get updated to 5.0, and then you can reinstall MongoDB 6.0.\nCode:{\"t\":{\"$date\":\"2022-09-15T15:52:43.611+02:00\"},\"s\":\"I\", \"c\":\"CONTROL\", \"id\":23403, \"ctx\":\"initandlisten\",\"msg\":\"Build Info\",\"attr\":{\"buildInfo\":{\"version\":\"6.0.1\",\"gitVersion\":\"32f0f9c88dc44a2c8073a5bd47cf779d4bfdee6b\",\"modules\":[],\"allocator\":\"system\",\"environment\":{\"distarch\":\"x86_64\",\"target_arch\":\"x86_64\"}}}}\n...\n{\"t\":{\"$date\":\"2022-09-15T15:52:44.717+02:00\"},\"s\":\"F\", \"c\":\"CONTROL\", \"id\":20573, \"ctx\":\"initandlisten\",\"msg\":\"Wrong mongod version\",\"attr\":{\"error\":\"UPGRADE PROBLEM: Found an invalid featureCompatibilityVersion document (ERROR: Location4926900: Invalid featureCompatibilityVersion document in admin.system.version: { _id: \\\"featureCompatibilityVersion\\\", version: \\\"4.4\\\" }. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility. :: caused by :: Invalid feature compatibility version value, expected '5.0' or '5.3' or '6.0. See https://docs.mongodb.com/master/release-notes/5.0-compatibility/#feature-compatibility.). If the current featureCompatibilityVersion is below 5.0, see the documentation on upgrading at https://docs.mongodb.com/master/release-notes/5.0/#upgrade-procedures.\"}}\n/usr/local/var/mongodbmongod"}, {"role": "assistant", "content": "Text:when I try to run brew services list I still see mongodb-community error 15872 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist does this file also need to be owned by ds or root ?The plist file should be owned by your user. It seems you\u2019ve got you system in a weird state. I am not sure how that would have happened. I don\u2019t think that there should be anything in your home directory that is not owned by you.\nCode:brew services listmongodb-community error 15872 root ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plistdsrootplist"}, {"role": "user", "content": "Text:Ok, let me try those 2 things you mentioned and will come here an update.1.deleting all the previous data (I can actually reimported again from a dump)\n2. changing also the permissions on my home folder\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: Connect ECONNREFUSED 127.0.0.1:27017 in Mongodb Compass and tags: ['node-js', 'compass', 'mongodb-shell', 'server']"}, {"role": "user", "content": "Text:I restarted my computer to try to update it, and before restarting, I was also working on another project. Now, my project with a node.js backend is giving me this error:and my mongodb compass is giving me: connect ECONNREFUSED 127.0.0.1:27017 . My operating system is macOS Big Sur.In a post on stackoverflow, someone suggested restarting the mongod process and connecting again. I tried following those instructionsmac-mongodb , but when I go to 'From a new terminal, issue the following: mongosh \u2019 my terminal gave me command not found: mongosh . I also tried testing it with PATH=\"/usr/local/opt/mongodb-community@4.4/bin\" mongo MongoDB shell version v4.4.13 and I still got Error: couldn't connect to server 127.0.0.1:27017, with connection refused.Does anyone know how to fix this? I would really appreciate any help or advice. Thank you\nCode:reason: TopologyDescription {\n type: 'Single',\n setName: null,\n maxSetVersion: null,\n maxElectionId: null,\n servers: Map(1) {\n 'localhost:27017' => ServerDescription {\n address: 'localhost:27017',\n error: Error: connect ECONNREFUSED 127.0.0.1:27017\n at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1132:16) {\n name: 'MongoNetworkError'\n },\n roundTripTime: -1,\n lastUpdateTime: 58154302,\n lastWriteDate: null,\n opTime: null,\n type: 'Unknown',\n topologyVersion: undefined,\n minWireVersion: 0,\n maxWireVersion: 0,\n hosts: [],\n passives: [],\n arbiters: [],\n tags: []\n }\n },\n stale: false,\n compatible: true,\n compatibilityError: null,\n logicalSessionTimeoutMinutes: null,\n heartbeatFrequencyMS: 10000,\n localThresholdMS: 15,\n commonWireVersion: null\n }\nconnect ECONNREFUSED 127.0.0.1:27017mongodmongoshcommand not found: mongoshPATH=\"/usr/local/opt/mongodb-community@4.4/bin\" mongo MongoDB shell version v4.4.13Error: couldn't connect to server 127.0.0.1:27017,"}, {"role": "assistant", "content": "Text:I am not an expert, just another user, but I believe this set of steps could help youUpon start it seems to me that Mongodb server generates a lock that blocks another process to take that port (this may be fully false).Test this ls /tmp/mongodb-27017*, because it is a temporary file you can very well remove it.Then restart the server, and see if it connects.\nCode:ls /tmp/mongodb-27017*"}, {"role": "assistant", "content": "Text:ECONNREFUSED 127.0.0.1:27017Means that NO mongod instance is running at the given host 127.0.0.1 and port 27017. Yes the solution is to start mongod.because it is a temporary file you can very well remove itNever do that unless you know absolutely what you are doing.Executing the command mongosh or mongo is not how you start mongod. Since you seem uncertain about the difference between the mongod server and the mongosh/mongo client, you might one to take the course MongoDB Courses and Trainings | MongoDB University.\nCode:"}, {"role": "assistant", "content": "Text:Why not? Likely the process shut down unexpectedly on the update and if the process is down I see no trouble doing it\u2026also bc OP is testing in localhost\u2026\nCode:"}, {"role": "assistant", "content": "Text:You seem to know what you are doing.The original poster do not seem to know, so he asked a question.One day he may delete the file to solve another issue. Restart the server and corrupts its data.That is why I wrote,Never do that unless you know absolutely what you are doing.If you know what you are doing then yes go ahead and delete it.\nCode:"}, {"role": "assistant", "content": "Text:Was anyone able to give a straight answer on this? I have the exact same problem\nCode:"}, {"role": "assistant", "content": "Text:The straight answer isECONNREFUSED 127.0.0.1:27017Means that NO mongod instance is running at the given host 127.0.0.1 and port 27017. Yes the solution is to start mongod.\nCode:"}, {"role": "assistant", "content": "Text:no it\u2019s not, this is no answertry to see the exact problem else we\u2019ll go around and around. I even went to compass and reconnect and it\u2019s refusingif I start mongod in anyway I have tried i got always denials like this one:==> Successfully started mongodb-community (label: homebrew.mxcl.mongodb-commu\nMac-do-Rateiro:Mongodb pedro$ mongo\nMongoDB shell version v5.0.6\nconnecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb\nError: couldn\u2019t connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :\nconnect@src/mongo/shell/mongo.js:372:17\n@(connect):2:6\nexception: connect failed\nexiting with code 1\nMac-do-Rateiro:Mongodb pedro$ sudo mongo\nPassword:\nMongoDB shell version v5.0.6\nconnecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb\nError: couldn\u2019t connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :\nconnect@src/mongo/shell/mongo.js:372:17\n@(connect):2:6\nexception: connect failed\nexiting with code 1\nMac-do-Rateiro:Mongodb pedro$ mongod\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.923+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:23285, \u201cctx\u201d:\"-\",\u201cmsg\u201d:\u201cAutomatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols \u2018none\u2019\u201d}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.923+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cNETWORK\u201d, \u201cid\u201d:4915701, \u201cctx\u201d:\"-\",\u201cmsg\u201d:\u201cInitialized wire specification\u201d,\u201cattr\u201d:{\u201cspec\u201d:{\u201cincomingExternalClient\u201d:{\u201cminWireVersion\u201d:0,\u201cmaxWireVersion\u201d:13},\u201cincomingInternalClient\u201d:{\u201cminWireVersion\u201d:0,\u201cmaxWireVersion\u201d:13},\u201coutgoing\u201d:{\u201cminWireVersion\u201d:0,\u201cmaxWireVersion\u201d:13},\u201cisInternalClient\u201d:true}}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.924+01:00\u201d},\u201cs\u201d:\u201cW\u201d, \u201cc\u201d:\u201cASIO\u201d, \u201cid\u201d:22601, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cNo TransportLayer configured during NetworkInterface startup\u201d}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.924+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cNETWORK\u201d, \u201cid\u201d:4648602, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cImplicit TCP FastOpen in use.\u201d}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cW\u201d, \u201cc\u201d:\u201cASIO\u201d, \u201cid\u201d:22601, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cNo TransportLayer configured during NetworkInterface startup\u201d}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cREPL\u201d, \u201cid\u201d:5123008, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cSuccessfully registered PrimaryOnlyService\u201d,\u201cattr\u201d:{\u201cservice\u201d:\u201cTenantMigrationDonorService\u201d,\u201cns\u201d:\u201cconfig.tenantMigrationDonors\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cREPL\u201d, \u201cid\u201d:5123008, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cSuccessfully registered PrimaryOnlyService\u201d,\u201cattr\u201d:{\u201cservice\u201d:\u201cTenantMigrationRecipientService\u201d,\u201cns\u201d:\u201cconfig.tenantMigrationRecipients\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:5945603, \u201cctx\u201d:\u201cmain\u201d,\u201cmsg\u201d:\u201cMulti threading initialized\u201d}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:4615611, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cMongoDB starting\u201d,\u201cattr\u201d:{\u201cpid\u201d:4972,\u201cport\u201d:27017,\u201cdbPath\u201d:\"/data/db\",\u201carchitecture\u201d:\u201c64-bit\u201d,\u201chost\u201d:\u201cMac-do-Rateiro\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:23403, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cBuild Info\u201d,\u201cattr\u201d:{\u201cbuildInfo\u201d:{\u201cversion\u201d:\u201c5.0.6\u201d,\u201cgitVersion\u201d:\u201c212a8dbb47f07427dae194a9c75baec1d81d9259\u201d,\u201cmodules\u201d:[],\u201callocator\u201d:\u201csystem\u201d,\u201cenvironment\u201d:{\u201cdistarch\u201d:\u201cx86_64\u201d,\u201ctarget_arch\u201d:\u201cx86_64\u201d}}}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:51765, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cOperating System\u201d,\u201cattr\u201d:{\u201cos\u201d:{\u201cname\u201d:\u201cMac OS X\u201d,\u201cversion\u201d:\u201c20.6.0\u201d}}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.926+01:00\u201d},\u201cs\u201d:\u201cI\u201d, \u201cc\u201d:\u201cCONTROL\u201d, \u201cid\u201d:21951, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cOptions set by command line\u201d,\u201cattr\u201d:{\u201coptions\u201d:{}}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.937+01:00\u201d},\u201cs\u201d:\u201cE\u201d, \u201cc\u201d:\u201cNETWORK\u201d, \u201cid\u201d:23024, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cFailed to unlink socket file\u201d,\u201cattr\u201d:{\u201cpath\u201d:\"/tmp/mongodb-27017.sock\",\u201cerror\u201d:\u201cPermission denied\u201d}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.937+01:00\u201d},\u201cs\u201d:\u201cF\u201d, \u201cc\u201d:\"-\", \u201cid\u201d:23091, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\u201cFatal assertion\u201d,\u201cattr\u201d:{\u201cmsgid\u201d:40486,\u201cfile\u201d:\u201csrc/mongo/transport/transport_layer_asio.cpp\u201d,\u201cline\u201d:989}}\n{\u201ct\u201d:{\"$date\":\u201c2022-06-12T14:30:39.937+01:00\u201d},\u201cs\u201d:\u201cF\u201d, \u201cc\u201d:\"-\", \u201cid\u201d:23092, \u201cctx\u201d:\u201cinitandlisten\u201d,\u201cmsg\u201d:\"\\n\\n***aborting after fassert() failure\\n\\n\"}orMac-do-Rateiro:Mongodb pedro$ mongoshCurrent Mongosh Log ID: 62a5eaac9f0a57c1d0ed9dd0Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.4.2MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017\nCode:mongodb-community"}, {"role": "assistant", "content": "Text:no it\u2019s not, this is no answerWell, I think it is and what you posted just demontrates it.You try to start mongo twice before trying to start mongod. So you get the error because mongod is not running.You then try to start mongod, but it fails because some permission denied error.You then try to connect with mongosh and still get the error. Of course you get the error mongod was not started. see #2 above.The process mongod must be running before you try to connect.As to why mongod does not start, the it looks like mongod was started by root (or a user different from your current user) and wad not terminated correctly since the shutdown cleanup usually done has not been completed.Try to manually delete the offending file and try to start mongod again. You should use systemctl or something lioe that to start mongod rather than manually as it behaves better when the computer shuts down.\nCode:"}, {"role": "assistant", "content": "Text:Well at least this is more infoSteve, the first time i did it was mongod and it always get the same answer. This is a little bit more complicated for sure.Now, your point on mongod started by root can be a logical cause but I am not sure to manually delete the \u201coffending file\u201d as you said, which leads to my question : what do you mean on the shutdown cleanup and how delete a \u201cwhat is\u201d offending file\nCode:"}, {"role": "assistant", "content": "Text:The offending file is the file mentionned in the error message you get when starting mongod.\u201cmsg\u201d:\u201cFailed to unlink socket file\u201d,\u201cattr\u201d:{\u201cpath\u201d:\"/tmp/mongodb-27017.sock\",\u201cerror\u201d:\u201cPermission denied\u201d}}When mongod terminates gracefully, the socket file above and some other lock files that are used to communicate or ensure the integrity of data directories are deleted so that the next startup can proceed. When mongod terminate abruptly, it cannot delete such files and locks.\nCode:"}, {"role": "assistant", "content": "Text:ok, good, so, how should I manually delete this file without making any mistake?\nCode:"}, {"role": "assistant", "content": "Text:/tmp/mongodb-27017.sockCheck owner/permissions on this filels -lrt /tmp/mongodb-27017.sockShutdown all mongods if any running and then remove this fileIf it is owned by root you have to use sudo rm\nAfter removing the file start mongod with sysctl as steevejSteeve Juneau suggested\nCode:"}, {"role": "assistant", "content": "Text:it worked after doing this:\nsudo rm -rf /tmp/mongodb-27017.sock\n(delete the file)brew services restart mongodb-community@5.0\n(restart services)brew services list\n(to check services and went \u201cgreen\u201d started)mongo\n(to start mongo, as well as connect with the compass, everything went ok after this)thank you all for the patience, hope it won\u2019t happen more often\nCode:"}, {"role": "assistant", "content": "Text:well for me, all i had to do is search for \u2018services\u2019 on my windows. scrolled down to MongoDB services and started it and went back to reconnect it on compass. it worked\nCode:"}, {"role": "assistant", "content": "Text:solution is as steevej said, to start monogDB first, and you can do so sudo systemctl start mongod if you\u2019re using ubuntu/linux, for windows give it a google search, or better yet look into mongoDB docs https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/i just faced this and was able to fix this by starting mongoDB, happy learning \nCode:sudo systemctl start mongod"}, {"role": "assistant", "content": "Text:I was getting the same error and I followed your solution and it worked for me as well.\nThanks \nCode:"}, {"role": "assistant", "content": "Text:open the setup there is an option to repair in it\nthat worked for me. i have mongodb v 6\nCode:"}, {"role": "assistant", "content": "Text:Hello Pedro, I\u2019m having the same issue but I dont see such file at all in the tmp folder on our server (Ubuntu 20.04)\nCode:"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: The Journey of #100DaysofCode (@eliehannouch) and tags: ['100daysofcode']"}, {"role": "user", "content": "Text:Hello folks, happy to join the #100DaysofCode inspired by @henna.s \nIn this amazing journey, I\u2019ll be sharing with you my daily progress learning Golang (moving from Node JS, Python). Starting from a hello world program at day-01 till finishing the adventure at day-100 with a complete API integrated with MongoDB. What is Golang? Golang, an open-source, compiled, and statically typed programming language designed by Google. Built to be simple, high-performing, readable, efficient, and concurrent nature. Used for server-side programming, game development, cloud-based programming, command line tools and more.Why Golang? The above command creates a go.mod file to track your code\u2019s dependencies. So far, the file includes only the name of your module and the Go version your code supports. But as you add dependencies, the go. mod file will list the versions your code depends on.Let\u2019s quickly analyze our simple first hello world go program package main: tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the package \u201cmain\u201d will be the entry point of our executable programimport \u201cfmt\u201d: here we are importing the fmt package, that allows us to format basic strings, values, or anything and print them or collect user input from the console or write into a file using a writer or even print customized fancy error messages.Finally we are defining our main function using the func keyword, that print for us a normal String using the fmt.Println function.And now let\u2019s run our main.go file using the following command to see the function result on the console \ngo run main.go\nimage1508\u00d7248 44.5 KB\nThat was everything for our Day-01 Hello world in Golang. Stay tuned in the coming days for some amazing and advanced topics, going from zero To hero in GO \nCode:day-01 go mod init yourModuleName or go mod init example.com/moduleName\n Example: go mod init hello\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello folks, Happy to Join the 100daysofcode!\")\n}\npackage mainimport \u201cfmt\u201dfmt.Printlnmain.gogo run main.go"}, {"role": "assistant", "content": "Text:Hello @eliehannouch,Super glad to see you being part of the #100Days of Journey\u2026 and happy that I played a part in inspiring you.We should spread some more noise around this. I can\u2019t wait to see your progress in these 100 days. Wish you all the best Cheers, \nCode:"}, {"role": "user", "content": "Text:Hello folks, Here we go, new day Day-02 and some new knowledge gained in Golang. Today we will dive in the GoLang data types.Go is a statically typed language. Which means that variable types are known at compile timeGo use type inference where the compiler can infer the type of a certain variable without explicitly specify it by the developersSigned Integer Types (int8, int16, int, int32, int64)Unsigned Integer Types (uint8, byte, uint16, uint, uint32, uint64, uintptr)Others (bool, float32, float64, complex64, complex128)\nimage600\u00d7600 52.7 KB\nString is a data type that represent a slice of bytes that are UTF-8 encoded. Strings are enclosed with double quotes.\nstrExample := \"Hello everyone, this a string\"We can get the String length by typing the following\n len([]rune(strExample)), or len(strExample)We can use the rune() function to convert string to an array of runesMoving from String to rune\nCode:(int8, int16, int, int32, int64uint8, byte, uint16, uint, uint32, uint64, uintptrbool, float32, float64, complex64, complex128int32 str:= 'B'\n fmt.Println(rune(str))\n // Output: 66\nstrExample := \"Hello everyone, this a string\" len([]rune(strExample)), or len(strExample)rune() strExample := \"Hello GoLang\"\n fmt.Println([]rune(strExample))\n\n Output: [72 101 108 108 111 32 71 111 76 97 110 103]\n type productID int type productPrice float64"}, {"role": "user", "content": "Text:It\u2019s Day03 \nHello folks glad to share with you a new day dealing with golang and exploring it alongside my daily work.\nToday we will talk more about the package system in go, its advantages, and how to deal with them and explore some of them in an example.What is a Package in simple terms ?In simple terms a package is a container or a box that contains multiple functions to perform specific tasks.When using packages, we can organize our Go code into reusable units.To use name aliasing in Go packages we can simply say:\n import s \"strings\", and here we can use s when calling the package instead of stringsTo solve a common problem of importing unused packages we can simply put a blank identifier before its definition\n_ \u201cfmt\u201d, and in this case no error will appearHow to import a package in Go ?To import a package, simply we can use the import keyword as following:\n import \u201cfmt\u201dIn the above import statement we have imported the fmt package, that is used to format basic strings, values, inputs, and outputs. And now after importing it all the available functions can be used on the fly inside our go file.Let\u2019s explore the fmt package quickly and some of its basic functionsAll these functions and much more can be used on the fly after importing the fmt packageExample to showcase how to deal with these packagesHow to create a custom package in Golang ?\nCode: import s \"strings\"s_ \u201cfmt\u201d import \u201cfmt\u201dfmtfmtPrint()Println() Scanf():fmtimport \u201cstrings\u201dCompare()Join():ToLower():ToUpper():// tells the Go compiler that the package should compile as\n// an executable program instead of a shared library\npackage main\n \n// here we are importing multiple packages in a single import\nimport (\n \"fmt\"\n \"strings\"\n)\n \nfunc main() {\n \n // transforming the string content to lower case\n lower := strings.ToLower(\"THE COMMUNITY IS THE BEST PLACE TO GROW\")\n fmt.Println(lower)\n \n checkTxt := \"Hello everyone, this is a test\"\n \n // checking if the checkTxt string contains a substring called everyone\n doesItContain := strings.Contains(checkTxt, \"everyone\")\n fmt.Println(doesItContain)\n // Output: true\n \n // making an array of strings\n arrayOfStrings := []string{\"I love\", \"Go Lang\", \"and\", \"MongoDB\"}\n fmt.Println(arrayOfStrings)\n //output: [I love Go Lang and MongoDB]\n \n // joining the array content into one string, separated by a space\n fromArrToString := strings.Join(arrayOfStrings, \" \")\n fmt.Println(fromArrToString)\n // output: I love Go Lang and MongoDB\n}\n\n//First we need to declare the package using the following piece of code: \npackage simplecalculator\n\n// create a simple addTwoNumbers function\nfunc addTwoNumbers(num1, num2 int) int {\n\treturn num1 + num2\n }\n\npackagesimplecalculatoraddTwoNumbers"}, {"role": "user", "content": "Text:Hello folks, every day is a new challenge. And today marks the 4th day in our amazing journey where we will make a quick intro about the modules system in Golang. What is a module? What is the benefit of using a module in Golang? **How to initialize a new module in Go? **What does this command do? \nCode:go. mod file module helloworld\n go 1.17\n module example.com/my/thing\n go 1.17\n\n require example.com/other/thing v1.0.2\n require example.com/new/thing/v2 v2.3.4\n\nor\n module example.com/my/thing\n go 1.17\n\n require (\n\t example.com/other/thing v1.0.2\n\t example.com/new/thing/v2 v2.3.4\n\t)\n"}, {"role": "user", "content": "Text:Hello friends, the 5th day is done , a new day, and some new knowledge in Golang. In today post we will review the conditionals in Golang, how they differ from other programming languages. We will also talk about loops and how to deal with them. I hope you will enjoy reading the post First, let make a quick refresher on what conditionals are all about in any programming language?What is an if statement and how it works in Golang? In simple terms we can define them a decision-making statement that guide a program to take decisions based on a specific condition, where it execute on a set of code it the specified condition is met (true) or on the other if it does not met (false)In Go, we don\u2019t use brackets around the condition itselfIf statement can be used without an else A statement can precede the conditionals and any declared var in the statement is available in all other branches In Golang there is no ternary operator , so we need to write a full if else statement to achieve the same result.Example illustrating how the if statement work in GoLangWhat is a while loop? Does it exist in Golang? And how can we replace it Loops In Go First of all let\u2019s remember, what does loops are all about in programming before diving in the Go editionIn computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached. Example for loops, while, do-whileIn Go, the only looping construct is for, so let\u2019s explore the different ways we can deal withExample:\nCode:truefalse package main\n \n import \"fmt\"\n \n func main() {\n \n // If condition without an else clause\n var i int = 300\n if i%6 == 0 {\n fmt.Println(i, \"is divisible by 6\")\n }\n // simple and without parenthesis \ud83e\udd70 \n if 20%2 == 0 {\n fmt.Println(\"20 is even\")\n } else {\n fmt.Println(\"20 is odd\")\n }\n \n // Statement initialization with If condition\n if n := 50; n < 0 {\n fmt.Println(n, \"is negative\")\n } else if n < 10 {\n fmt.Println(n, \"has 1 digit\")\n } else {\n fmt.Println(n, \"has multiple digits\")\n }\n }\n package main\n \n import (\n \"fmt\"\n )\n \n func main() {\n i := 0\n for i < 50 {\n fmt.Println(\"i =\", i)\n i += 2\n \n }\n package main\n \n import \"fmt\"\n \n func main() {\n \n // The for loop that replace while in Golang\n i := -2\n for i <= 3 {\n fmt.Println(i)\n i++\n }\n //A classical for loop.\n for j := 0; j <= 10; j++ {\n fmt.Println(j)\n }\n \n // We can use the continue keyword to jump to the next iteration of the loop\n for n := 0; n <= 5; n++ {\n if n%2 == 0 {\n continue\n }\n fmt.Println(n)\n }\n \n // A for without condition will loop repeatedly until you break out of it.\n for {\n fmt.Println(\"loop\")\n break\n }\n }\n"}, {"role": "user", "content": "Text:Hey folks, it\u2019s the 6th day / 100, let\u2019s explore some new topics in Golang, and make this journey a funny one .In today post, we will talk about some of the basic data structures in Golang, starting with arrays, and slices.Arrays in Golang What is an array in Golang?Slices in GolangWhat are Slices in Golang? \nCode: Arrays Example package main\n \n import \"fmt\"\n \n func main() {\n \n var a [5]int\n fmt.Println(\"Initial values of a:\", a) // Output: [0 0 0 0 0]\n \n // Here we are assigning the 3rd and 5th element of the array to the values -3 and 20 respectively.\n a[2] = -3\n a[4] = 20\n fmt.Println(\"setting data:\", a)\n fmt.Println(\"retrieving:\", a[3])\n \n // Array length\n fmt.Println(\"array length:\", len(a))\n \n // declaring an integer array with 5 elements\n b := [5]int{1, 2, 3, 4, 5}\n fmt.Println(b)\n \n // Creating a 2D array and filling it with values\n var twoD [2][3]int\n for i := 0; i < 2; i++ {\n for j := 0; j < 3; j++ {\n twoD[i][j] = i + j\n }\n }\n fmt.Println(\"Two dimensional array:\", twoD) // Output: [[0 1 2] [1 2 3]]\n }\n\ncaplenmakeappendcopySlices Example package main\n \n import (\n \"fmt\"\n )\n \n func main() {\n // Delcare empty slice of type int or string or any other type\n var sliceinteger []int\n \n // Create a new slice by filling it with data\n //var filledslice = []int{1, 2, 3, 4}\n \n // Checking the capacity of a slice using the built in cap\n fmt.Println(\"Capacity: \", cap(sliceinteger))\n \n // Checking the length of a slice using the built in function len\n fmt.Println(\"Length: \", len(sliceinteger))\n \n // Create a new slice using the make keyword, with a length of 10 and type string\n var slicestring = make([]string, 10)\n \n // Add element to the end of a slice using the append method\n slicestring = append(slicestring, \"MongoDB\", \"GoLang\", \"NodeJS\", \"Python\")\n \n // copy a slice to another\n a := []int{1, 2, 3}\n b := make([]int, 5, 10)\n copy(b, a)\n b[3] = -4\n b[4] = 5\n fmt.Println(b) // Output: [1 2 3 -4 5]\n \n // Slicing tips\n slice := []int{1, 2, 3, 4}\n fmt.Println(slice[:]) // Output: [1 2 3 4]\n fmt.Println(slice[1:]) // Output: [2 3 4]\n fmt.Println(slice[:1]) // Output: [1]\n fmt.Println(slice[:2]) // Output: [1 2]\n fmt.Println(slice[1:4]) // Output: [2 3 4]\n }\n"}, {"role": "user", "content": "Text:Hello folks, today marks our 7th day / 100 , so let\u2019s learn some amazing new topics in Golang, moving everyday toward our goal the DAY 100. Today, we will continue our tour with a new data structure the Golang map and then we will discover the range and learn how to deal with it in go. Maps in Golang What is a Map in Golang and how we can use it? \u2776 A built-in associative data type, that maps keys to values\u2777 Used for fast lookups, deletion, and data retrieval based on keys\u2778 Store data in key-value pairs style\u2779 A map cannot have identical keys\u277a Called dicts or hashes in other languages\u277b Maps are unordered, So each time we iterate through them , we can get a new different order of elements\u277c Now let\u2019s move to an example, where we will illustrate how we can create maps in different ways, initialize them with data, change these data, delete them and much more\u2026Golang Maps ExampleRange in Golang What is a range in Golang, and how it works? \nCode:rangedictshashesGolang Maps Example package main\n \n import (\n \"fmt\"\n )\n \n func main() {\n \n // First we are declaring a map with string keys and string values.\n var programmingLanguages map[string]string\n \n // Now we are initializing the map using the make function\n programmingLanguages = make(map[string]string)\n \n // Adding Data to the map\n programmingLanguages[\"p1\"] = \"GoLang\"\n programmingLanguages[\"p2\"] = \"JavaScript\"\n programmingLanguages[\"p3\"] = \"Python\"\n programmingLanguages[\"p4\"] = \"Rust\"\n \n fmt.Println(programmingLanguages) // Output: map[p1:GoLang p2:JavaScript p3:Python p4:Rust]\n \n // Access a certain value from the map\n var c1Value = programmingLanguages[\"p2\"]\n fmt.Println(c1Value) // Output: JavaScript\n \n // Delete a value (Rust) from the map\n delete(programmingLanguages, \"p4\") // Output: map[p1:GoLang p2:JavaScript p3:Python]\n \n // Iterate over the map using the for loop\n for language, key := range programmingLanguages {\n fmt.Println(language, key)\n }\n \n // Get the map length\n mapLength := len(programmingLanguages)\n fmt.Println(mapLength) // Output: 3\n }\n\nrangeGolang Range example package main\n \n import \"fmt\"\n \n func main() {\n \n numbers := []int{1, 2, 3, 4}\n sum := 0\n \n // Iterating through the array of numbers and calculating the sum\n // We are passing _ as first argument, as the index in our case does not matter\n for _, num := range numbers {\n sum += num\n }\n fmt.Println(\"sum:\", sum)\n \n // Here we are iterating through the array and both the index and the numbers matter\n // The first argument i --> represent the index\n // The second argument num --> represent the number\n for i, num := range numbers {\n if num == 3 {\n fmt.Println(\"index:\", i)\n }\n }\n \n // Here we are iterating through the map\n // key reperent the available keys in the map (g,m)\n // value represent the value associated with each key\n techStack := map[string]string{\"g\": \"Golang\", \"m\": \"MongoDB\"}\n for key, value := range techStack {\n fmt.Printf(\"%s -> %s\\n\", key, value)\n // Output: g -> Golang\n // m -> MongoDB\n }\n \n // In maps , using range we can iterate only over keys\n for key := range techStack {\n fmt.Println(\"key:\", key)\n // Output: key: g\n // key: m\n }\n \n // In Golang we can use the range on strings over Unicode code points\n // i represent the index\n // r represent the rune\n for i, r := range \"Golang\" {\n fmt.Println(i, r)\n // Output; \n /*\n i r\n ------\n 0 71\n 1 111\n 2 108\n 3 97\n 4 110\n 5 103\n */\n }\n }\n\n"}, {"role": "user", "content": "Text:Hello, Hello folks how it\u2019s going on, today marks our DAY / 100 . GOLANG is going very smoothly till now . I hope you are enjoying my posts, and getting to learn more about this new in demand technology.In today post, we will talk about functions, their types, and how we can use them in Golang What is a function ? How to declare a normal function in Golang ?Multiple Return functions in GolangVariadic Functions in Golang Coming from its name, a variadic function is simply a one that takes a variable number of args. And each time we call the function we can pass a varying number of arguments of the same typeA variadic function can be simply created by adding an ellipsis \u201c\u2026\u201d to the final parameter , as the example shown belowExample\nCode:func\tfunc ourFirstFunction (parameter1, parameter2 ,parameter3 \u2026) datatype {\n\t\t// The function logic written here \u2026\n\t}\n package main\n \n import \"fmt\"\n \n // A function that takes 2 integers and return the result as an int\n func addition(a int, b int) int {\n return a + b\n }\n \n // If we have multiple arguments of the same type, we can pass the type\n // to the last argument among them, like a,b,c int\n func addition2(a, b, c int) int {\n return a + b + c\n }\n \n // A golang function without any return type\n func subtract(num1 int, num2 int) {\n result := 0\n result = num1 - num2\n fmt.Println(result)\n }\n \n func main() {\n \n res1 := addition(1, 2)\n fmt.Println(\"1+2 =\", res1)\n \n res2 := addition2(1, 2, 3)\n fmt.Println(\"1+2+3 =\", res2)\n \n subtract(5, 3)\n \n }\n\n package main\n \n import \"fmt\"\n \n func values() (int, int) {\n return 10, 70\n }\n \n func main() {\n \n a, b := values()\n fmt.Println(a) // Output: 10\n fmt.Println(b) // Output: 70\n \n // When we use the blank identifier on the first argument\n // only the second one get returned and vice versa\n _, c := values()\n fmt.Println(c) // Output: 70\n }\n\n package main\n \n import \"fmt\"\n \n // A function called addition that take a variable number of arguments\n func addition(nums ...int) {\n // 1st: We are printing the numbers\n fmt.Print(nums, \" \")\n // 2nd: Iterating through the numbers and adding them\n total := 0\n for _, num := range nums {\n total += num\n }\n // 3rd: printing the total\n fmt.Println(total)\n }\n \n func main() {\n \n // Calling the function with 2 args\n addition(1, 2) // Output: [1 2] 3\n // Calling the same function with 3 args\n addition(1, 2, 3) // Output: [1 2 3] 6\n \n // And finally here we are passing an array of numbers as an argument to the function\n nums := []int{1, 2, 3, 4}\n addition(nums...) // Output: [1 2 3 4] 10\n }\n"}, {"role": "user", "content": "Text:Hello folks, another day, and some new progress in this amazing journey. Today marks our 9th day in the 100days code challenge. And in today\u2019s post, we will continue our tour on some new concepts in Golang. Where we will talk about anonymous functions, nested functions, and closures What is an anonymous function in Golang ?An anonymous function can be assigned to a variable.ExampleWhat is a nested function ? And does Golang support such functions ? A nested function is a function which is defined within another function, the enclosing function.A nested function is it self invisible outside of its immediately enclosing function, but can see (access) all local objects (data, functions, types, etc.) of its immediately enclosing function.Golang allow us to deal with such functions, on the fly.ExampleA function that returns a function ??Yeh, in Golang we can simply create a function that returns a function, let us understand how we can do that, in the following example.ExampleWhat is a closure in Golang ??A function that references variables outside its body or scope, or in other words we can define it as an inner function that has an access to the variables in the scope in which it was created.Example:\nCode: package main\n \n import \"fmt\"\n \n func main() {\n \n // anonymous function\n var helloCommunity = func() {\n fmt.Println(\"Hello, MongoDB community \ud83e\udd70 \ud83d\ude80\")\n }\n \n // calling the function\n helloCommunity()\n \n // anonymous function with arguments\n var multiplication = func(a, b int) int {\n return a * b\n }\n // passing arguments to the anonymous function\n fmt.Println(\"Multiplication result: \",multiplication(5, 4))\n }\n \n package main\n \n import (\n \"fmt\"\n str \"strings\"\n )\n // The outer function\n func hello(name string) {\n \n // The inner function using the args name of its enclosing function\n var displayName = func() {\n updatedName := str.ToUpper(name)\n fmt.Println(\"Hello\", updatedName)\n }\n // call the inner function\n displayName()\n }\n func main() {\n // Call the parent outer function\n hello(\"elie\")\n // Output: Hello ELIE\n }\n \n package main\n import \"fmt\"\n \n func helloWorld() func() {\n \n return func() {\n fmt.Println(\"Hello World\")\n }\n \n }\n \n func main() {\n \n functionInsideFunction := helloWorld()\n functionInsideFunction()\n }\n \n package main\n \n import (\n \"fmt\"\n \"strings\"\n )\n // The outer function that return another anonymous function\n func displayNameInLoweCase(name string) func() string {\n greeting := \"Hello,\"\n // The anonymous inner function that return\n // the name passed from the outer function concatenated with a string in lower case\n return func() string {\n transformedName := strings.ToLower(name)\n return greeting + transformedName\n }\n }\n func main() {\n \n lower := displayNameInLoweCase(\"JOHN\")\n fmt.Println(lower())\n }\n \n"}, {"role": "user", "content": "Text:Hello community , hope you are enjoying the journey and learning some amazing things in Golang. \nA day means some new progress and time to share what I learned to this amazing\u200b:heart_eyes: community. So everything stays from the community to the community. In today\u2019s post we will talk about recursion, how we can create recursive functions\u2753 and deal with them, then we will move to discover structs and their role in Golang.What does recursion mean ? When should I use recursion The recursion approach is used mainly when we need to solve problems that can be broken down into smaller and repetitive problems. The recursion approach win when the problem to be solved have many possible branches and these branches are too complex to iterate through themExample: Searching in a file systemAnd now let\u2019s move to learn a new amazing concept in Golang. Structs !!\u00a0 What is a struct in Golang And how can we create and manipulate them ??\nCode:structs package main\n \n import \"fmt\"\n \n func factorial(n int) int {\n if n == 0 {\n return 1\n }\n // the factorial function calling itself, until solving the problem\n return n * factorial(n-1)\n }\n \n func fibonacci(n int) int {\n if n < 2 {\n return n\n }\n // fibonacci calling it self\n return fibonacci(n-1) + fibonacci(n-2)\n }\n \n func main() {\n fmt.Println(factorial(4)) // Output: 24\n \n fmt.Println(fibonacci(6)) // Output: 8\n }\n\nStructstypestruct namestruct type StructureName struct {\n // structure definition \n }\n package main\n \n import (\n \"fmt\"\n )\n \n func main() {\n \n // A basic car struct\n type Car struct {\n carModel string\n productionYear int\n carColor string\n }\n \n // declaring a struct that represent a User\n type User struct {\n firstName string\n lastName string\n phoneNumber string\n age int\n jobTitle string\n // use the car struct as a user defined data type\n car Car\n }\n \n // To define a struct instance\n var car Car\n \n // assign value to car struct\n car = Car{\n carModel: \"BMW\",\n productionYear: 2019,\n carColor: \"Black\",\n }\n \n // Here we are creating a new User based on the defined struct\n // and adding a predefined car to it as a nested struct\n user1 := User{\"John\", \"Doe\", \"000000\", 25, \"Software Engineer\", car}\n fmt.Println(user1)\n // Output: {John Doe 000000 25 Software Engineer {BMW 2019 Black}}\n \n // To access a certain field from user1 we use the dot\n fmt.Println(user1.firstName, \"-\", user1.jobTitle)\n // Output: John - Software Engineer\n \n // To access a nested struct\n fmt.Println(user1.car.carModel) // Output: BMW\n \n }\n"}, {"role": "user", "content": "Text:Hello folks, a day is here, let\u2019s wrap it up with some new content and a lot of fun . To mark this amazing day as completed we should dive into a new interesting topic in Golang !! In today\u2019s post , we will make a gentle intro on Golang methods, how we can deal with them and the difference between them and functions. What is a method in Golang ? It\u2019s simply a normal function or we can say that a method behaves like a function but with a special receiver type. The receiver in the Golang method can be a struct or a non struct type.We can define the same method on different struct types , for example if we have a Rectangle \u25ad and a Square struct. We can simply define an Area method on both of them.Why methods in Golang ? Golang is not\u200b:no_entry: a complete object oriented programming language and hence it does not support the classes architecture. Methods were created with an aim to represent the same behavior done in classes. Methods allow the grouping of all functions that belong to the same struct type together. How to define a method in Golang ? To define a method in Golang we use the same function style with one extra parameter which is the receiver type between the func keyword and the method name Syntax Example:Methods Example And we reached the end of our gentle intro defining what methods are all about, and how we can deal with them. In tomorrow\u2019s post we will dive more into methods and make some more advanced operations on them after introducing the pointers in Go. Stay tuned for the coming post, and let\u2019s make this journey an amazing one, where all of us can learn and take some new skills in a funny way \nCode:\tfunc (t Type) nameofMethod (param1, param2, \u2026) {\n\t\t// Method logic define here in the body\n\t}\n package main\n \n import \"fmt\"\n import \"math\"\n \n // Defining a Rectangle struct with 2 attributes height and width\n type Rectangle struct {\n height int\n width int\n }\n \n // Defining a Circle with a radius of type float\n type Circle struct {\n radius float64\n }\n \n // Here we are defining an Area method that deal with the rectangle struct\n func (r Rectangle) Area() int {\n return r.height * r.width\n }\n \n // Defining a method that deal with the rectangle struct and compute the perimeter\n func (r Rectangle) perimeter() int {\n return 2*r.width + 2*r.height\n }\n \n // As we can see here we are defining the same method Area\n // defined above, with a different receiver which is Circle\n func (c Circle) Area() float64 {\n return math.Pi * c.radius * c.radius\n }\n \n func main() {\n rec := Rectangle{\n height: 12,\n width: 4,\n }\n fmt.Printf(\"The Area of the rectangle %d\\n\", rec.Area())\n //Output: The Area of the rectangle 48\n\n fmt.Printf(\"The Perimeter of the rectangle %d\\n\", rec.perimeter())\n // Output: The Perimeter of the rectangle 32\n\n circ := Circle{\n radius: 4.2,\n }\n fmt.Printf(\"The area of the circle %f\", circ.Area())\n // Output: The area of the circle 55.417694\n }\n\n"}, {"role": "user", "content": "Text:Day 12 is already here . Hope you are doing well and enjoying your journeys to the maximum. So guys, it\u2019s time to continue and dive more into some interesting topics in Golang, to wrap up the day successfully. In today\u2019s post, we will talk about pointers in Go, their role and where to use them. Moving from some theoretical definitions to an interactive funny example that illustrate the targeted topics in a clear way What is a pointer in Golang ? A pointer is simply a normal \ud83e\udd79 variable that stores the address of a certain object stored in the memory.A pointer points to different variables with different data types like int , string , bool and more and only stores their memory address in hexadecimal format. In Golang, pointers are called special variables.Why do we use pointers in Go ? Pass by reference Pass by value What is a dereference operator in Golang pointer ? What is the address operator in Golang ?How to declare a pointer in Golang ?Create a pointer using the keyword Functions with pointers \nCode:intstringboolarraystructinterface*&var pointerName *TypepointerNameTypeintstring package main\n \n import \"fmt\"\n \n func main() {\n // A variable of type int\n var integerNumber int\n integerNumber = 34 // A number of type int\n \n // A pointer of type string\n var stringPointer *string\n \n // A pointer of type int\n var integerPointer *int\n \n // integerPointer pointing to integerNumber\n integerPointer = &integerNumber\n \n fmt.Println(\"The address on which the pointer is pointing\", integerPointer)\n // Output: output in hex is 0x1400001c070\n \n fmt.Println(\"The value of the variable to which the pointer is pointing\", *integerPointer)\n // Output: The value is: 34\n \n // To change the value of the variable via the pointer we use:\n \n *integerPointer = 45\n \n fmt.Println(\"The new value of the variable integerNumber is: \", integerNumber)\n // Output: 45\n }\n \n package main\n \n import \"fmt\"\n \n func main() {\n \n // create a pointer using new()\n var newPointer = new(string)\n \n *newPointer = \"elie hannouch\"\n \n fmt.Println(newPointer) // 0x14000010230\n fmt.Println(*newPointer) // elie hannouch\n \n }\n\n package main\n \n import \"fmt\"\n \n func updateName(name *string) {\n // Using the dereference operator we change\n // value of the name variable\n *name = \"Elie Hannouch\"\n \n }\n \n func main() {\n // Name with initial value\n var name string = \"John Doe\"\n fmt.Println(\"The original name is\", name) // John Doe\n \n // Passing the address of the name variable to the updateName function\n updateName(&name)\n fmt.Println(\"The original name is now changed to\", name) // Elie Hannouch\n }\n\nstructsmethods"}, {"role": "user", "content": "Text:Hello, Hello, The 13th day is here. Okay folks let\u2019s keep the amazing journey going on. \nBefore marking our day as completed, let\u2019s dive more into some new and amazing topics in Golang. In yesterday post , we talked about pointers, how to use them and their benefits in Go, we also made a gentle intro on how we can utilize the power of pointers, when dealing with functions where we explored the concept of pass by reference vs the pass by value and how each of them deal with the code in different way, resulting in different results. Today we will dive more with pointers to explore how we can use them with structs and methods, and how they give us some extra power , when utilizing them correctly. In this post we will move from the theoretical definitions and explanations and get into an interactive example that shows us how we can add pointers to structs and methods. Pointers with structsMethods and PointersMethods in Golang ?: It\u2019s simply a normal function or we can say that a method behaves like a function but with a special receiver type In yesterday\u2019s post we explored the difference between pass by value and pass by reference in normal functions. Today we will explore Value vs Pointer receiver in methods.Value Receiver Pointer receiverA value receiver, take a copy of the type and simply pass it to the method, and in this case our method holds an object equal to the original one but each of them sit in a different memory location. And now any change happening on the passed object only affects the local one. Where the original object stay untouchedOn the other hand, A pointer receiver: take the address of the original object and pass it to the method. And now the method has a reference to the original object location and any modification will affect this original one directlyExampleAnd now to analyze our code, using the value receiver which takes a copy of the object, the carModel name changed only inside the function but the change is not reflected in the main function On the other hand by using the pointer receiver which takes the address of the object, when we changed the price to 10000 this price affected the car2 object found in the main function after calling the PointerReceiver method on it.So now we can demonstrate that when we use a pointer receiver , any occurring change will affect the original object and when using the value receiver the changes only affect the copied object locally.\nCode: package main\n \n import \"fmt\"\n \n func main() {\n \n // Here we are defining a user struct with some specific attributes.\n type User struct {\n firstName string\n lastName string\n age int\n email string\n phoneNumber string\n }\n \n // And now we are gonna initialize a user instance\n user1 := User{\n firstName: \"John\",\n lastName: \"Doe\",\n age: 30,\n email: \"john@example.com\",\n phoneNumber: \"555-555-5555\",\n }\n \n // create a pointer with struct type\n // to save the user address\n \n var pointer1 *User\n \n // Save the person1 struct address in the defined pointer\n pointer1 = &user1\n \n // Print the pointer struct\n fmt.Println(pointer1)\n // Output: &{John Doe 30 john@example.com 555-555-5555}\n \n // change the struct attributes values via the created pointer\n pointer1.firstName = \"Jonas\"\n pointer1.phoneNumber = \"111-111-1111\"\n fmt.Println(pointer1)\n // Updated Output: &{Jonas Doe 30 john@example.com 111-111-1111}\n }\n\n package main\n \n import (\n \"fmt\"\n )\n \n type Car struct {\n carModel string\n price int\n }\n \n func ValueReceiver(c Car) {\n c.carModel = \"BMW\"\n fmt.Println(\"Inside ValueReceiver method: \", c.carModel)\n }\n \n func PointerReceiver(c *Car) {\n c.price = 10000\n fmt.Println(\"Inside PointerReceiver method: \", c.price)\n }\n func main() {\n car1 := Car{\"Nissan\", 8500}\n car2 := &Car{\"Mercedes\", 12800}\n ValueReceiver(car1)\n fmt.Println(\"Inside Main after calling the value receiver : \", car1.carModel)\n PointerReceiver(car2)\n fmt.Println(\"Inside Main after calling the pointer receiver : \", car2.price)\n }\n \n // output:\n // Inside ValueReceiver method: BMW\n // Inside Main after calling the value receiver : Nissan\n // Inside PointerReceiver method: 10000\n // Inside Main after calling the pointer receiver : 10000\n\n"}, {"role": "user", "content": "Text:Hello family , yeah family the best word we can say in the world . Today I\u2019m here to share with you our big mongo DB family some amazing news. Okay, let me wrap this special day here, in this special place with our amazing community. In today post I\u2019m not going to talk about some technical topics, no it\u2019s not the target now.In this special day, me and @darine_tleiss the sister that God gave me, we closed a chapter, and we are officially graduated as computer scientist. My friends, I\u2019m here today to tell you all, keep your friends by your side . They are the God grace and the life gift . \ud835\udfef years passed during which I learned a lot in this wonderful major. I got to know many classmates from whom I learned many lessons . And today I\u2019m telling you all, and the joy fills my heart\u200b:heart:. We marked the old chapter as completed and we opened a one towards a better future and a challenging adventure . Together as best friends , we will fight till the end to craft a future we deserve. In front \u27ac of you all I would like to thank my best and closest sister Darine , for everything you did for me. We defied the odds and conquered the problems \ud83c\udd87. You were the one who heard my problems, accepted my good and bad . Thanks for all your sacrifices . And today I\u2019m asking God to keep you by my side until infinity. \u221e\u221e \nCode:"}, {"role": "user", "content": "Text:Hello folks, a new day and some new progress. In today\u2019s post we will resume the technical content to dive more in Golang and explore some new amazing concepts. In our last Golang post, we talked about pointers and their role and how we can use them with structs, functions, methods and more. In today\u2019s post we will talk about interfaces, their role and how we can utilize them. Starting from some theory information and wrapping up with an example that shows us how we can use interfaces in a real example. What is an interface in Golang ?What happens if a struct does not implement all the interface methods ? Now we reached the post end. In tomorrow\u2019s post we will dive more into mixins and then we will introduce the functions concept, to utilize more the power of this amazing technology. \nCode: package main\n \n import (\n \"fmt\"\n \"math\"\n )\n \n // Here we are defining the interface geometry\n // That define 2 signatures the area and perimeter in an abstract way\n type geometry interface {\n area() float64\n perim() float64\n }\n \n // Here we have a rectangle struct with 2 attributes width and height\n type rectangle struct {\n width float64\n height float64\n }\n \n // The circle struct with the radius attribute\n type circle struct {\n radius float64\n }\n \n // With the rectangle struct we are implementing the interface\n // with all the signatures available inside of it\n func (r rectangle) area() float64 {\n return r.width * r.height\n }\n func (r rectangle) perim() float64 {\n return 2*r.width + 2*r.height\n }\n \n // Same here for the circle functions that implement the geometry interface\n func (c circle) area() float64 {\n return math.Pi * c.radius * c.radius\n }\n \n func (c circle) perim() float64 {\n return 2 * math.Pi * c.radius\n }\n // a generic measure function\n func measure(g geometry) {\n fmt.Println(g)\n fmt.Println(g.area())\n fmt.Println(g.perim())\n }\n \n func main() {\n r := rectangle{width: 3, height: 4}\n c := circle{radius: 5}\n \n measure(r)\n measure(c)\n }\n\n"}, {"role": "user", "content": "Text:Hello friends, here we go, the 16th day is already here . Let\u2019s finish it successfully by taking some new information, to extend our existing knowledge in the Golang world. In today\u2019s post, I\u2019ll move a little bit out of track and share with you some interesting information in String functions, that help us manipulate and deal with strings easily. So in this post we will explore the strings package , which gives us a lot of useful string-related functions to be used out of the box. \nCode: package main\n \n import (\n \"fmt\"\n s \"strings\"\n )\n \n var p = fmt.Println\n \n func main() {\n \n p(\"Contains: \", s.Contains(\"test\", \"es\"))\n p(\"Count: \", s.Count(\"test\", \"t\"))\n p(\"HasPrefix: \", s.HasPrefix(\"test\", \"te\"))\n p(\"HasSuffix: \", s.HasSuffix(\"test\", \"st\"))\n p(\"Index: \", s.Index(\"test\", \"e\"))\n p(\"Join: \", s.Join([]string{\"a\", \"b\"}, \"-\"))\n p(\"Repeat: \", s.Repeat(\"a\", 5))\n p(\"Replace: \", s.Replace(\"foo\", \"o\", \"0\", -1))\n p(\"Replace: \", s.Replace(\"foo\", \"o\", \"0\", 1))\n p(\"Split: \", s.Split(\"a-b-c-d-e\", \"-\"))\n p(\"ToLower: \", s.ToLower(\"TEST\"))\n p(\"ToUpper: \", s.ToUpper(\"test\"))\n \n \n // Output\n /*\n Contains: true\n Count: 2\n HasPrefix: true\n HasSuffix: true\n Index: 1\n Join: a-b\n Repeat: aaaaa\n Replace: f00\n Replace: f0o\n Split: [a b c d e]\n ToLower: test\n ToUpper: TEST\n */\n }\n\n"}, {"role": "user", "content": "Text:Hello folks, a new day is here, let\u2019s wrap it successfully by learning some new techniques to format a string in Golang. In yesterday post we talked about the string functions and how we can use them to manipulate strings in Go In today\u2019s post we will learn the different ways to format a string, by moving from the boring theory part, to directly moving on directly to an interactive example to learn from it. Exercise Let\u2019s end this amazing post now, I hope you can learn some amazing stuff from it, and stay tuned for tomorrow\u2019s post where we will explore new interesting topics. \nCode: package main\n \n import (\n \"fmt\"\n )\n \n type point struct {\n x, y int\n }\n \n func main() {\n \n p := point{5, 7}\n \n fmt.Printf(\"struct: %v\\n\", p)\n // The %v print the struct values as they are in the\n // Output: struct: {5 7}\n \n fmt.Printf(\"struct: %+v\\n\", p)\n // The %+v print the struct values with the struct field names\n // Output: struct: {x:5 y:7}\n \n fmt.Printf(\"struct: %#v\\n\", p)\n // The %#v print the struct values, field names and the syntax representation\n // Output: struct: main.point{x:5, y:7}\n \n fmt.Printf(\"type: %T\\n\", p)\n // The %T print the type of the variable\n // Output: type: main.point\n \n fmt.Printf(\"int: %d\\n\", 123)\n // The %d print the value in base 10 representation\n // Output: 123\n \n fmt.Printf(\"bin: %b\\n\", 14)\n // The %b print the value in binary\n // Output: 1110\n \n fmt.Printf(\"char: %c\\n\", 33)\n // The %c print the char corresponding to the integer\n // char: !\n \n fmt.Printf(\"hex: %x\\n\", 456)\n // The %x print the value in hexadecimal\n // Output: 1c8\n \n fmt.Printf(\"float1: %f\\n\", 78.9)\n // The %f print the float number in it's basic form\n // Output: 78.900000\n \n fmt.Printf(\"float2: %e\\n\", 123400000.0)\n fmt.Printf(\"float3: %E\\n\", 123400000.0)\n // The %e and %E print the float value in different way\n // Output: 1.234000e+08 or 1.234000E+08\n \n fmt.Printf(\"str: %s\\n\", \"\\\"string\\\"\")\n // The %s is used to print the string\n // Output: \"string\"\n \n fmt.Printf(\"str: %q\\n\", \"\\\"string\\\"\")\n // The %q is used to double quote strings\n // Output: \"\\\"string\\\"\"\n \n fmt.Printf(\"str: %x\\n\", \"hex this\")\n // The %x render the string in base 16\n // Output: 6865782074686973\n \n fmt.Printf(\"pointer: %p\\n\", &p)\n // The %p is used to print the representation of the pointer\n // Output: 0x1400012a010\n \n }\n\n"}, {"role": "user", "content": "Text:Hello folks, hope you are doing well, and you are learning some amazing things in this amazing tech world. In yesterday\u2019s post, we talked about string formatting in Golang. And in today\u2019s post we will define the regular expressions in Golang. How to use them and to do so ? What is a regular expression ?Application of regular expression ? Simple parsing.The production of syntax highlighting systems. Data Validation. Data Scraping (especially web scraping)Data wrangling.Example\nCode:regexregexpfindfind and replace package main\n \n import (\n \"fmt\"\n \"regexp\"\n )\n \n func main() {\n \n match, _ := regexp.MatchString(\"p([a-z]+)ch\", \"peach\")\n fmt.Println(match)\n \n r, _ := regexp.Compile(\"p([a-z]+)ch\")\n \n fmt.Println(r.MatchString(\"peach\"))\n \n fmt.Println(r.FindString(\"peach punch\"))\n \n fmt.Println(\"idx:\", r.FindStringIndex(\"peach punch\"))\n \n fmt.Println(r.FindStringSubmatch(\"peach punch\"))\n \n fmt.Println(r.FindStringSubmatchIndex(\"peach punch\"))\n \n fmt.Println(r.FindAllString(\"peach punch pinch\", -1))\n \n fmt.Println(\"all:\", r.FindAllStringSubmatchIndex(\n \"peach punch pinch\", -1))\n \n fmt.Println(r.FindAllString(\"peach punch pinch\", 2))\n \n fmt.Println(r.Match([]byte(\"peach\")))\n \n r = regexp.MustCompile(\"p([a-z]+)ch\")\n fmt.Println(\"regexp:\", r)\n \n fmt.Println(r.ReplaceAllString(\"a peach\", \"\"))\n \n /*\n true\n true\n peach\n idx: [0 5]\n [peach ea]\n [0 5 1 3]\n [peach punch pinch]\n all: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]\n [peach punch]\n true\n regexp: p([a-z]+)ch\n a \n a PEACH\n */\n \n }\n\n"}]} +{"messages": [{"role": "system", "content": "You are an assistant of MongoDB Community who is responsible for answering the questions related with MongoDB."}, {"role": "system", "content": "The following conversation has title: The journey of #100DaysOfCode (@Darine_Tleiss) and tags: ['100daysofcode']"}, {"role": "user", "content": "Text:Hello everyone , I am Darine from Lebanon MUG happy to join the #100DaysOfCode inspired by @henna.s, where I\u2019ll share my daily progress learning some amazing JS stuff.For today, the #Day1 day in this amazing journey, I\u2019ll be sharing some amazing information about the Document Object Model in JavaScript.What is DOM ? The Document Object Model is a programming interface for web documents. It represents these documents as nodes and objects, so in this case the programming language like JS can interact with the page to change the content, the style or even the structure.DOM !== JAVASCRIPT DOM is not a programming language, neither a part of the JavaScript language, but instead it\u2019s a Web API used to build websites, and JS without it wouldn\u2019t have any model of the web pages, and we as JS developers cannot make those cool animations that we see around in most of today websites. Where all of these animations are made simply by manipulating the DOM.Dom Manipulation It\u2019s the interaction process with the JS DOM API to create, modify, style, or delete elements without a refresh. It also promotes user interactivity with browsers.DOM Tree\n950\u00d71024 56.6 KB\n\nLet\u2019s explore the above tree, and get to know some of it\u2019s important parts:\nCode:"}, {"role": "assistant", "content": "Text:Hello @Darine_Tleiss ,Welcome to MongoDB Community Absolutely Delighted to know that I inspired you This has been an amazing journey for me and I am thinking of getting back to it sometime in July now I wish you all the best on your self-discovery and please feel free to reach out anytime when you need Cheers, \nCode:"}, {"role": "user", "content": "Text:Today we will explore some of the document object model functions that help us accessing different parts of our web page, or even create a new one from scratch.First let\u2019s explore some of the basic DOM methods that help, retrieving and selecting certain sections of the document starting with:document.documentElement\nReturn the root element of the document, for example the html element for the HTML documents.document.querySelector('p')\nA method that returns the first element that matches a CSS selector.document.querySelectorAll('p')\nA method that returns a static NodeList representing a list of the document\u2019s elements that match the specified group of selectors.\nOutput:document.getElementById(\"section1\");\nA method that returns an element with a specified value or returns null if the element does not exist.document.getElementsByTagName('tagName');\nA method that returns an HTMLCollection of elements with the given tag, and the returned collection is live, meaning that it updates itself automatically And if we pass * as a tagName the method returns all the elements of the document.document.getElementsByClassName('btn');\nA method that returns an array-like object of all child elements which have all of the given class name(s).And Now it\u2019s time, to learn more on how we can create a new element using DOM, and add some content to it : const message = document.createElement('div');\nHere we are creating a div using the .createElement method and saving it to a message const.message.classList.add('greeting-message');\nIn the above code, we are adding a className (greeting-message) to our newly created div with the help of classList.add method.message.innerHTML = \u2018Hello dear community, I\u2019m so happy joining this amazing journey and sharing my daily progress\u2019 \nHere by using the .innerHTML method we are embedding some content to the created div.const body = document.querySelector('body\u2019);\nbody.append(message);\nAnd finally we append it to the body section of our HTML document using the following piece of code.\nCode:document.documentElementdocument.querySelector('p')document.querySelectorAll('p')NodeList(6) [p, p, p, p, p, p]\n0: p\n1: p\n2: p\n3: p\n4: p\n5: p\nlength: 6\n[[Prototype]]: NodeList\ndocument.getElementById(\"section1\");document.getElementsByTagName('tagName');document.getElementsByClassName('btn');const message = document.createElement('div');message.classList.add('greeting-message');message.innerHTML = \u2018Hello dear community, I\u2019m so happy joining this amazing journey and sharing my daily progress\u2019const body = document.querySelector('body\u2019);body.append(message);"}, {"role": "user", "content": "Text:Hello friends , a new day == a new progress \nToday we will learn how to create documents using DOM, add elements to it, prepend, append and manipulate them Lets create a new document so we can add, remove and manipulate their elements\nlet newDoc = new Document();\nHere we are initialising a new document called newDoc.Let\u2019s create some html elements to add them to our newly created documentlet html = document.createElement(\u201chtml\u201d);\nHere using the document.createElement function we are creating a new HTML element to be appended to our documentnewDoc.append(html)\nThe .append method, add the html element to the document and the doc structure become as following:\nNow let\u2019s expand the html element and add some new elements to it\nlet head = document.createElement(\u201chead\u201d);\nlet body = document.createElement(\u201cbody\u201d);html.append(body)Let\u2019s anaylze our code and see the generated document\nAfter creating the html document, we have created 2 new elements, the body and the head.\nAnd using the .append method, we\u2019ve added the body to the html and the structure became as following:\nAnd now how can add the head element, before the body one ??Easy we can simply use the .before method that inserts a set of Node or string objects in the children list of this Element\u2019s parent, just before this ElementSo we execute it as following:body.before(head);After preparing the main document structure, let\u2019s create some elements to be added to our body. So we can perform some experiments on them let h1 = document.createElement(\u201ch1\u201d);\nlet p = document.createElement(\u201cp\u201d);\nlet div = document.createElement(\u201cdiv\u201d);\nbody.append(p,div)So finally let add the missing h1 element as a first child to the body.How ? Using the body.prepend() method that inserts a set of Node objects or string objects before the first child of the Element.body.prepend(h1)Finally for today let\u2019s add some text with a className \u2018content\u2019 to our paragraph, get rid of the unnecessary created h1 and move the paragraph to become the child of the empty div.p.innerHTML = \u201cHello everyone, here we are inserting some text to the p element using the write method\u201dp.className = \u201ccontent\u201d\nbody.removeChild(h1)\ndiv.appendChild(p)\n1600\u00d7440 81.3 KB\n\nCode:"}, {"role": "user", "content": "Text:Hello friends , hope you are excited to learn something new in the amazing world of JavaScript. Today marks the 4th day in this challenging and fun journey. And Now it\u2019s time to continue the exploration process of the DOM.First of all we are gonna start exploring the different elements children, their parents & siblings, how we can access them and what operations we can perform on.How can we check if a certain element has some children ? Select the targeted element by its ID, or className as following\nconst r = document.getElementById('root')After selecting it, we can easily run the following command which returns either true or false, where true means the element has some childrens and vice versa.How can we list the childNodes of a certain element if they exist ? Using the Element.childNodes function that returns a live NodeList of child nodes, where the first child node is assigned with index 0, and so on.Now let\u2019s dive into our elements and learn more about how we can access a first child, a last one, how we can change, delete them and more \u2026To access the first child , using the Node.firstChild property that returns the first child in the tree.To access the last child , using the Node.lastChild that returns the last child of the nodeTo access an element at a certain position we can access it simply by specifying it index, using the Element.children[index]To delete a certain child , we can use the removeChild() method that returns the specified child if it exists from the DOM then returns it.\nExample:And here the first child with the index 0 is removed from the tree and the new set is:Moving from childrens to parents & siblings. Let\u2019s now learn more about them, how to access some of them and more \u2026To access the parent of a certain element we can simply use the following property Element.parentNode, which return the parent of the targeted element as following:To access the siblings of a certain element, we have to use the basic properties of the Node.nextSibling that return the next sibling in the tree and the Node.previousSibling that return the previous one.\nExample:\nCode:const r = document.getElementById('root')r.hasChildNodes()\ntrue\n const r = document.getElementById('root')\n r.childNodes\n \n NodeList(3) [ul#nav-access.a11y-nav, div.page-wrapper.category-api.document-page, footer#nav-footer.page-footer]\n 0: ul#nav-access.a11y-nav\n 1: div.page-wrapper.category-api.document-page\n 2: footer#nav-footer.page-footer\n length: 3\n [[Prototype]]: NodeList\n const r = document.getElementById('root')\n r.firstChild\n
    \u200b\u2026 <\u200b/ul>\nconst r = document.getElementById('root')\n r.lastChild\n
    \u2026\u200b
    \nconst r = document.getElementById('root')\nr.children[1]\n
    \u200b\u2026\u200b \nconst r = document.getElementById('root')\nr.removeChild(r.children[0])\n
      \u200b\u2026
    \u200b\n HTMLCollection(2) [div.page-wrapper.category-api.document-page, footer#nav-footer.page-footer, nav-footer: footer#nav-footer.page-footer]\n 0: div.page-wrapper.category-api.document-page\n 1: footer#nav-footer.page-footer\n nav-footer: footer#nav-footer.page-footer\n length: 2\n [[Prototype]]: HTMLCollection\nconst r = document.getElementById('root')\nr.parentNode\n \u2026\u200b \u200b\nconst element = document.getElementById('p2')\nelement.previousSibling\n