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

[System] The following conversation has title: MongoServerSelectionError: connection closed and tags: ['node-js', 'connecting', 'atlas-cluster']

[User]
Text:Hi,
When I try to submit a form in a localhost:5000 website, I am getting  aerror.  I’m unsure why this is happening. I don’t know if it’s  because for some reason it’s listing 3 in servers: Map(3) {...}, but I would really appreciate any advice on how to fix this.
Code:MongoServerSelectionError: connection <monitor> closed
    at Timeout._onTimeout (/Users/_/Desktop/Clone/node_modules/mongodb/lib/sdam/topology.js:318:38)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(3) {
      'cluster0-shard-00-00.d1mrz.mongodb.net:27017' => [ServerDescription],
      'cluster0-shard-00-01.d1mrz.mongodb.net:27017' => [ServerDescription],
      'cluster0-shard-00-02.d1mrz.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'atlas-lkpac7-shard-0',
    logicalSessionTimeoutMinutes: undefined
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}
servers: Map(3) {...}

[Assistant]
Text:Have you whitelisted your IP?type: ‘ReplicaSetNoPrimary’
Reading time: 3 min read

Code:

[User]
Text:Thank you! That worked. I had seen something that mentioned whitelisting an IP for a similar issue, but I was not sure where in mongodb that was, so that article was perfect!
Code:


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

[System] The following conversation has title: How to query an array of objects to match any of the provided values? and tags: ['queries']

[User]
Text:Hey guys, so in my schema i have an array of objects, it looks like this:So, what I need is: I want to query through this array of objects and check if it will match any of the values I provided. For example, lets suppose I have a name and a email - I need to build a query providing the name and the email and check if, in this array, the name or the email already exists.But, I don’t want to query for exact match, i mean, i want to check if the email or the name already exists there, but both could be in separated objects.On the example I provided, lets suppose I have the name frank and the email daniel@email.com and I make a query with both - both already exists so i do something with that…The purpose is to avoid duplicated entries for example.
Code:entries: [
  {
    name: 'frank',
    age: 15,
    email: 'frank@email.com'
  },
{
    name: 'daniel',
    age: 18,
    email: 'daniel@email.com'
  }
]

[Assistant]
Text:Hi,You can do it like this:Working exampleMongo playground: a simple sandbox to test and share MongoDB queries online
Code:db.collection.find({
  "entries.name": "frank",
  "entries.email": "daniel@email.com"
})

[User]
Text:Ah cool, didnt think it was so easy. Thank you
Code:

[User]
Text:What about if I need to put the id of the collection? Like findOne by id and search on the entries array of objects
Code:

[Assistant]
Text:Hi,Can you give an example and expected output?
Code:

[User]
Text:I have a collection with the entries array of objects (name, email, age). I want to build a query where I provide some values, like age and email for example. It will retrieve any array of object that contains name or the mail or the age provided.For example, if I want to query for email, i would do like that:
Code:db.collection.findOne({_id, "entries.name": name});

[Assistant]
Text:If you specify _id in your query, there is no point in specifying anything else because _id is unique.
Code:

[User]
Text:You didnt get it. I have the id of the collection where the array is located at.collectionI have th id of the collection and i need to find any match inside the array of objects, to avoid duplicates.
Code:

[Assistant]
Text:You didnt get it.Indeed. I do not get it.  The statementdb.collection.findOne({_id, "entries.name": name});asked to findOne document from the collection named collection, because you do db.collection.findOne.  And you want the document to match the query { _id , “entries.name” : name }.The _id in the above is notthe id of the collection where the array is locatedThe _id in the above is the unique _id of one and only one document in the collection named collection.  So what specifying entries.name can do in your query is to prevent you from find the document with the given _id.
Code:db.collection.findOne({_id, "entries.name": name});

[User]
Text:yea, sorry, exactly, the id of the document that contains the entries inside. Look the query you wrote, thats right, but what if instead of just name i want to query for email and name? like two arguments?
Code:

[Assistant]
Text:@NeNaD has already provided the solution for that.You can do it like this:
Code:db.collection.find({
  "entries.name": "frank",
  "entries.email": "daniel@email.com"
})

[User]
Text:But this query would be querying all the documents. I want to query only one specific document (which I have the id). The array of objects is inside this document
Code:

[Assistant]
Text:But this query would be querying all the documents.Yes it willI want to query only one specific document (which I have the id)Now it makes more sense thanI have th id of the collection and i need to find any match inside the array of objectsSo the answer should make more sense too.Documents in collectionThe following query will find all documents.However this one, will only find _id:0 because it is specified in the query.The next one will only find _id:0.  It does not find _id:1 because name:2 and age:3 is not both true for the same element.In all cases, all elements of entries are sent in the result.  To restrict the element of entries that are sent you need to use
orI think both only project the first element that matches.  The only way I know to project more element will be to use $filter within an aggregation pipeline.
Code:{ "_id" : 0 ,
  "entries" :  [
    { "name" : 2 , "age" : 3 } ,
    { "name" : 4 , "age" : 5 } ,
    { "name" : 6 , "age" : 7 }
  ]
}

{ "_id" : 1 ,
  "entries" :  [
    { "name" : 2 , "age" : 5 } ,
    { "name" : 4 , "age" : 3 }
  ]
}
{ "entries.name" : 2 , "entries.age" : 3 }
{ "_id" : 0 , "entries.name" : 2 , "entries.age" : 3 }
{ "entries" : { "$elemMatch" : { "name" : 2 , "age" : 3 } }


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

[System] The following conversation has title: View just certain fields from a documents and tags: ['queries', 'compass', 'mongodb-shell']

[User]
Text:I found this site : MongoDB query select and display only a specific field from the document?
and my question was how to view just certain fields from a documents.  The  particular statement is
db.querySelectDemo.find().pretty();  However there are some problems
#1.  Collection is not mentioned
#2.  with Mongosh from Compass, I dont see querySelectDemo - so smells like a private function
Any ideas ?
Thanks !
Code:

[Assistant]
Text:Hi @Andrew_Watts
Welcome to the community forum!!db.querySelectDemo.find().pretty()is represented using the format:
db.<collection-name>.find().pretty() where find() and pretty() are built-in functions to find all the documents and to display the documents in a formatted pattern respectively.Could you please confirm the following information from Compass:how to view just certain fields from a documents.To answer this, there could be multiple ways to view only selected fields from the collection.db.querySelectDemo.find({},{_id:0,UserName:true});Thanks
Aasawari
Code:db.<collection-name>.find().pretty()find()pretty()db.<collection-name>.aggregate( [ { $project : { _id : 0 , UserName : 1 } } ] )

[User]
Text:Thanks for you explanation -  I  did not explain clearly.
The compass  version is 1.31.2  / mongash works fine. I was puzzled how the tutorlal website could grab the collection without it being identified  - there’s lots I dont know but I thought either they werent using MongoDb  or theses some private function in use.  Thanks for showing me how the capability to view specific values of a document collection would work !
Code:

[User]
Text:Oh, I see now, the querypoing  tutorial name the coillection querySelectDemo  - how confusing !
Code:


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

[System] The following conversation has title: Sorting with mongoose - find() and tags: ['queries', 'node-js', 'mongoose-odm']

[User]
Text:I have a Model with {timestamps : true}.
I want that every time i create a new post it will show at the top of the page. I tried with .sort (createdAt: -1) but it didn’t work. Pls help and thankyou guys

Code:

[Assistant]
Text:Hi,Your query seams good.Can you check in the database if createdAt properties are added to the documents?Also, you can actually do the sorting with _id if it’s of the type ObjectId:
Code:createdAt_idModel.find().sort({ _id: -1 })

[User]
Text:I checked the database, the prop createdAt already added but something wrong with my database, it shows only one data even though i don’t use any query. As before, a list will be displayed.
And i tried sort with _id, same result. when i create a new post, it still shows at the end of the array

Screenshot 2022-04-18 1713211876×793 48.9 KB

Code:

[Assistant]
Text:Hi,Then the issue is not with sort. You have only one document inside the collection, so only that document will be returned.You should add more new documents and then check if the sort is working.
Code:sortsort

[User]
Text:You can see that Total Document is 7 - My posts alredy have 7 post diffirent ~.~
Code:


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

[System] The following conversation has title: Updating an object value in a nested array and tags: ['queries', 'node-js']

[User]
Text:I’ve been trying to use positional operators to update an object property value to no avail. The code is straightforward and should work based on what I’ve watched video-wise and read documentation-wise. However, I’ve received an error every time without being able to make any progress in solving it.Using a positional operator, I’m attempting to set the totalWishes of the specific banner type to 1 but receive the error below.Any and all help is appreciated.
Code:		await player.updateOne({ 'pity.type': type }, { $set: { 'pity.$.totalWishes': 1 } });

MongoServerError: Cannot create field 'type' in element

[Assistant]
Text:Hi @ProbablyPi ,For updating nested arrays specific elements you need to use a syntax called arrayFilters.See more examples here :Thanks
Pavel
Code:

[Assistant]
Text:Hi, can you please share a sample document where you are trying to update this?
Code:

[Assistant]
Text:Hi @shrey_batra ,The document will probably look like :The command should look something like :Thanks
Code:{
pity : [
{ type : xxx,
  totalWishes : 0
}
]
}
db.player.updateOne(
   {"pity.type" : type },
   { $set: { "pity.$[elem].totalWishes" : 1 } },
   { arrayFilters: [ { "elem.type": type } ] }
)

[Assistant]
Text:Hi and welcome to the forums @ProbablyPi,Second @shrey_batra  if you could please add:So we don’t assume too many details that may actually draw you back from doing it.
Code:

[User]
Text:Thank you @santimir ,The document looks like Pavel suggestedHowever, I’ve tried what Pavel suggested before I made this post, and not even that worked. The expected output is actually to increment totalWishes, but I thought there was an issue with using the $inc operator so I tried using $set to no avail.
Code:{
   "pity":[
      { "type":"weapon", "totalWishes":0 },
      { "type":"character", "totalWishes":0 },
      { "type":"standard", "totalWishes":0 }
   ]
}

[User]
Text:Hi Pavel,Thanks for the suggestion, however, I tried a similar method before making this post without any success. Though, I will continue to try today with the array filters you mentioned earlier and see if that is the solution I’ve been looking for.
Code:

[Assistant]
Text:@ProbablyPiTo update allOr with condition:That’s why I asked input and output. I may still be misunderstanding You can also filter in the first field, and use updateOne if necessary etc. You will work it out.
Code:db.collection.update({},
{
  $inc: {
    "pity.$[].totalWishes": 1
  }
})
db.collection.update({},
{
  $inc: {
    "pity.$[elem].totalWishes": 1
  }
},
{
  arrayFilters: [
    {
      "elem.type": "weapon"
    }
  ]
})

[User]
Text:@santimirTested with no errors! Though, the document itself doesn’t increment whatsoever. I’m quite confused now, I’ve double-checked that the types are correct, and made sure it’s fetching the correct document. Any clue why it isn’t incrementing? If it’s any help, I’m using mongoose ver 6.1.6
Code:

[Assistant]
Text:@ProbablyPiWould you share a screenshot of the code?Make sure you replace “collection” by the collection name, and that you’re in the right database. It may be useful to create a test collection if you haven’t done it already.Also, from mongoose docs:Model.update: Updates one document in the database without returning it.
Code:

[User]
Text:@santimirYep, in the right database and I’m using my proper collection, though upon logging it outputs{ acknowledged: false }Would this have anything to do with it? And as requested, here is the code I’m executingThe fetchPlayerData function looks like this.
If I can provide anything else that might help, please let me know.
Code:{ acknowledged: false }const player = await client.database.fetchPlayerData(application.user.id);

const test = await player.updateOne({}, {
$inc: { 'pity.$[elem].totalWishes': 1 },
arrayFilters: [{ 'elem.type': type }]
});
console.log(test);

[Assistant]
Text:Uhmm, I am not sure I can debug from that because I don’t know enough of Mongoose.But JIC it helps other users, what does client.database resolve to? And does it store fetchPlayerData() method?The acknowledge false may indeed come from updateOne(). You could also  console.log('log', player, 'and', application.user).
Code:client.databaseconsole.log('log', player, 'and', application.user)

[User]
Text:The client.database call returns the object below.I do know for 100% certainty that both player and application.user return what’s requested. I think it has to pertain with the mongo call itself. Previously I had to use .findIndex() on the player object and do pity.${typeIndex}.totalWishes and that seemingly worked. But it’s a bit slower than using strictly mongo methods.After doing a bit of looking, acknowledge false seems to be when the call failed to write to the database.
Code:client.database{
  _id: new ObjectId("61fcce41ae207a386fc5a003"),
  userId: '490243269096112129',
  totalWishes: 270,
  pity: [
    {
      type: 'standard',
      totalWishes: 10,
      fourStarPity: 0,
      fiveStarPity: 10,
      wishHistory: [Array]
    },
    {
      type: 'weapon',
      totalWishes: 0,
      fourStarPity: 0,
      fiveStarPity: 0,
      wishHistory: []
    },
    {
      type: 'character',
      totalWishes: 260,
      fourStarPity: 0,
      fiveStarPity: 70,
      wishHistory: [Array]
    }
  ],
  createdOn: 2022-02-04T06:56:59.521Z,
  lastUpdated: 2022-02-04T06:56:59.521Z,
  __v: 1
}
.findIndex()pity.${typeIndex}.totalWishes

[Assistant]
Text:So player is a Document instance, and you probably extended that or a parent class with the async methods. We should then read Document.updateOne()They use something like (mind the first field);Which sends the _id along.
Code:player.updateOne({
  $inc: {
    "pity.$[elem].totalWishes": 1
  }
},
{
  arrayFilters: [
    {
      "elem.type": "weapon"
    }
  ]
}, { w: 1 }, callback);

[User]
Text:@santimirSorry if it’s obvious, but what is w in this case?
Code:

[Assistant]
Text:Google about write concerns to get deeper into it.
Code:mongod

[Assistant]
Text:@ProbablyPi any luck?
Code:

[User]
Text:Hi @santimirI took a break for awhile, to take a look at the problem with fresh eyes. Using the code you provided above, provides this error Error: Could not find path "pity.0.type" in schema, do you think it may be smarter to use regular properties or objects instead of an array of objects?
Code:Error: Could not find path "pity.0.type" in schema

[Assistant]
Text:@ProbablyPi  that’s a shame. Maybe rewrite like this?It is not very clear t me from the mongoose docs if the arrayFilters should be in the same document. But now it looks the same than MongoDB docs at least.The last thing I could think of it is that some of those packages (maybe mongodb native driver) is outdated. You can check with npm outdated.I don’t think array of objects is a big deal, this is just part of learning how to use it. But you should try to make the Schema as simple as possible, keeping it useful.
Code:player.updateOne({
  $inc: {
    "pity.$[elem].totalWishes": 1
  }
},
{
  arrayFilters: [
    {
      "elem.type": "weapon"
    }
  ],
  w: 1
}, (e,r)=>console.log(e,r));
npm outdated


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

[System] The following conversation has title: Issues starting MongoDB on MacOS and tags: ['server', 'installation']

[User]
Text:I’ve installed MongoDB through my terminal using Homebrew. I did all the correct steps listed on their website. I get many errors when running  mongod  and  mongo .When I run  mongodWhen I run  mongo :
Code:mongodmongomongod{"t":{"$date":"2020-09-20T18:35:56.680-05:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2020-09-20T18:35:56.690-05:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2020-09-20T18:35:56.691-05:00"},"s":"I",  "c":"NETWORK",  "id":4648602, "ctx":"main","msg":"Implicit TCP FastOpen in use."}
{"t":{"$date":"2020-09-20T18:35:56.694-05:00"},"s":"I",  "c":"STORAGE",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":43856,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"Isaacs-MacBook-Air.local"}}
{"t":{"$date":"2020-09-20T18:35:56.694-05:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"4.4.0","gitVersion":"563487e100c4215e2dce98d0af2a6a5a2d67c5cf","modules":[],"allocator":"system","environment":{"distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2020-09-20T18:35:56.694-05:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Mac OS X","version":"19.5.0"}}}
{"t":{"$date":"2020-09-20T18:35:56.694-05:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}}
{"t":{"$date":"2020-09-20T18:35:56.696-05:00"},"s":"E",  "c":"NETWORK",  "id":23024,   "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Permission denied"}}
{"t":{"$date":"2020-09-20T18:35:56.696-05:00"},"s":"F",  "c":"-",        "id":23091,   "ctx":"initandlisten","msg":"Fatal assertion","attr":{"msgid":40486,"file":"src/mongo/transport/transport_layer_asio.cpp","line":919}}
{"t":{"$date":"2020-09-20T18:35:56.696-05:00"},"s":"F",  "c":"-",        "id":23092,   "ctx":"initandlisten","msg":"\n\n***aborting after fassert() failure\n\n"}
mongoMongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
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 :
connect@src/mongo/shell/mongo.js:362:17
@(connect):2:6
exception: connect failed
exiting with code 1

[Assistant]
Text:Hi @Isaac_Medina,It looks like a permissions problem:Is a mongod already running or the user running the process can’t unlink this file.Have you tried running with sudo…Best
Pavel
Code: file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Permission Denied

[Assistant]
Text:Hey
I’m stuck in kind of similar issue but when i try to run:
mongod:
i get this error

Screenshot 2022-04-13 at 6.16.00 PM1440×900 85.1 KB
could you help me resolve that error.
Code:

[Assistant]
Text:see if your mongo instance is up and runninguse command “sudo systemctl status mongodb”you should get a prompt for your admin passwordthen you should get read outif that’s green open a new tab and type mongoif it’s red, and you have only just set it up best to remove mongo and reinstall again
or you can try sudo systemctl start command on the mongo serviceIn this guide, we will walk you through the process to uninstall MongoDB from the three popular operating systems, i.e., Linux, Mac, and Windows.hopefully this helps.
Code:

[Assistant]
Text:The error message (the line with "s":"E") indicates that the file /tmp/mongodb-27917.sock cannot be removed (cannot unlink).It means that it is own by a user other than the current user.  Most likely a previous version was started as root.  May be it is still running.  Check that before using sudo to remove the file.Do notuse command “sudo systemctl status mongodb”to check the status of mongod when you start mongod manually like you did.To see if the socket is still being listen to, useTo see if a mongod is running, useBoth commands might be different on MacOS.You did not get an error for it, but I was under the impression that you could not use /data/db for mongod on MacOS.
Code:"s":"E"ss -tlnp | grep [2]7017
ps -aef | gre[ [m]ongod

[Assistant]
Text:I’m getting this error
when i try to create the folder with
sudo mkdir -p /data/db
i’m getting read only how to resolve that.

Screenshot 2022-04-14 at 10.51.49 AM1440×900 101 KB

Code:

[Assistant]
Text:and also this

Screenshot 2022-04-14 at 10.55.45 AM1440×900 224 KB

while running
mongod
in my terminal
Code:

[Assistant]
Text:On Macos access to root folder is removed.Thats why you get read only filesystem message
There is a difference between /data/db and ~/data/dbYour first command was correct.It says dir exists
Your data/db exists under your home dir
So include the full path in your config fileWhen you run just mongod without any params it starts mongod on default port and default dirpath /data/db.Since no access to /data/db(read only) it failed to start
Code:

[Assistant]
Text:I uninstalled mongodb compoletely and reinstlling it.
when i run mongod:
i get read only error. where can i create a dir. when i try to create one it shows read only filesystem in this what to do how to create a directory.

Screenshot 2022-04-14 at 5.36.40 PM1440×900 78.1 KB

Code:


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

[System] The following conversation has title: Mongod.service start command is not working after db path move and tags: []

[User]
Text:1.Stop MongoDB services
sudo systemctl stop mongod.service2.create a new directory in separate partition
mkdir /data/mongoDB/mongo3.Make sure that mongod user has privileges to read / write from that directory
chown mongod:mongod -R /data/mongoDB4.Copy the data folder of your old mongodb location to the new location
cp -R /var/lib/mongo/*  /data/mongoDB/mongo/5.create a copy of /etc/mongod.conf – for backup purposepath:
dbPath:
pidFilePath:change the pid file location in mongod.service file
/usr/lib/systemd/system/mongod.serviceRun below command to reflect changes done
systemctl daemon-reload8.Start mongodb services
sudo systemctl start mongod.service
Job for mongod.service failed because the control process exited with error code. See “systemctl status mongod.service” and “journalctl -xe” for detailsNOTE-i used below command and mongodb started functioning
mongod --confog=/etc/mongod.confCAN YOU HELP HERE…AM I MISSING  ANYTHING AND HOW CAN WE FIX mongod.service status???
Code:

[User]
Text:@Fabio_Ramohitaj any idea, how to fix
suprisingly in some servers it is working, and some doesnot
Code:

[User]
Text:we tried below options as well, still not workingOption 1:server rebootOption2:*repair mongo db with below commandmongod --dbpath /data/mongoDB/mongo –repair
Code:

[Assistant]
Text:Hi @Chinmaya_Das,
Unfortunately I’m out right now and I have no way to do a test, but I can advise you to check if all the paths in the configuration file are correct.
The problem is that the exit status 1 is a too generic error and it happened to me when I had a wrong path in the configuration file or a wrong option or a wrong indentation .Best regards and keep me updated.
Code:

[User]
Text:surprisingly in few servers it is working, and in few servers it is notI tried to replicate and cross check the permission, indentation, path ownership everything
still issue persists
Code:

[Assistant]
Text:Hi @Chinmaya_Das ,
I haven’ t any idea,
we can try to ask @Stennie_X or @chris for help .Regards
Code:

[User]
Text:@Stennie_X @chris --can you assist
Code:

[Assistant]
Text:Option2:*repair mongo db with below commandmongod --dbpath /data/mongoDB/mongo –repairHi @Chinmaya_Das ,I’d strongly discourage option #2 per the warnings in `mongod --repair’ documentation:i used below command and mongodb started functioning
mongod --confog=/etc/mongod.confIf mongod fails to start as a service but runs via manual invocation with the same config file, my guess would be that there is a problem with file or directory permissions that you are avoiding by running mongod as the root user. I would check permissions for any paths mentioned in your /etc/mongod.conf (step 6).ERROR: child process failed, exited with error number 1**
To see additional information in this output, start without the “–fork” option.**If permissions aren’t the issue, I’d try this suggestion.If you’re still stuck, please share more details including:Regards,
Stennie
Code:mongod --repair--repairmongod --repairmongodmongodroot/etc/mongod.conf

[User]
Text:
Code:-bash-4.2$ cat /etc/mongod.conf
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /data/mongoDB/log/mongod.log

# Where and how to store data.
storage:
  dbPath: /data/mongoDB/mongo
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# how the process runs
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /data/mongoDB/mongod.pid #location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.

#security:
security:
  authorization: enabled
#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options

#auditLog:

#snmp:

-bash-4.2$ cd /data
-bash-4.2$ ll
total 20
drwx------. 2 mongod mongod 16384 Nov 11 23:27 lost+found
drwx------. 4 mongod mongod  4096 Jan 11 11:49 mongoDB
-bash-4.2$ cd mongoDB
-bash-4.2$ ll
total 28
drwx------. 2 mongod mongod  4096 Jan 11 11:49 log
drwx------. 4 mongod mongod 16384 Jan 11 11:56 mongo
-rw-r--r--. 1 mongod mongod   862 Jun 29  2021 mongod.conf.bkpjab11
-rw-r--r--. 1 mongod mongod     6 Jan 11 11:49 mongod.pid
-bash-4.2$ mongod --version
db version v4.2.6
git version: 20364840b8f1af16917e4c23c1b5f5efd8b352f8
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
allocator: tcmalloc
modules: none
build environment:
    distmod: rhel70
    distarch: x86_64
    target_arch: x86_64
=====================================
-bash-4.2$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)

[User]
Text:mongod -f /etc/mongod.conf
systemctl start mongod.serice
Code:

[Assistant]
Text:Need output ofIf mongod was started by root, it is possible that the log file is now own by root and cannot be overwritten by user mongod.
Code:ls -l /data/mongoDB/log/
ls -l /data/mongoDB/mongo/

[User]
Text:@stevej
Code:-bash-4.2$ ls -l /data/mongoDB/log/
total 284
-rw-------. 1 mongod mongod 283709 Jan 12 23:35 mongod.log
-bash-4.2$ ls -l /data/mongoDB/mongo/
total 8379412
-rw-------. 1 mongod mongod     196608 Jan 12 09:02 collection-0--1245733199008363699.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-0--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:43 collection-0-2938523890601203458.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:43 collection-0-4663825045788152862.wt
-rw-------. 1 mongod mongod     131072 Jan 12 04:49 collection-0--5305699207077892184.wt
-rw-------. 1 mongod mongod      45056 Jan 12 04:49 collection-0-6066076875358285443.wt
-rw-------. 1 mongod mongod      45056 Jan 11 11:49 collection-0-9092172278719928609.wt
-rw-------. 1 mongod mongod      36864 Jan 12 21:35 collection-0--9202003834816367794.wt
-rw-------. 1 mongod mongod    2969600 Jan 12 06:31 collection-10--1809642965555131340.wt
-rw-------. 1 mongod mongod     561152 Jan 12 09:02 collection-10--5305699207077892184.wt
-rw-------. 1 mongod mongod    1388544 Jan 12 09:03 collection-11-3147801643784858223.wt
-rw-------. 1 mongod mongod  253083648 Jan 12 08:55 collection-12--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 collection-13-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-13--5305699207077892184.wt
-rw-------. 1 mongod mongod     118784 Jan 12 16:32 collection-15-3147801643784858223.wt
-rw-------. 1 mongod mongod   42283008 Jan 12 09:02 collection-16--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:40 collection-17-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-18--1809642965555131340.wt
-rw-------. 1 mongod mongod      61440 Jan 12 15:14 collection-18--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:41 collection-19-3147801643784858223.wt
-rw-------. 1 mongod mongod   21434368 Jan 12 09:02 collection-20--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 15:14 collection-2--1245733199008363699.wt
-rw-------. 1 mongod mongod      45056 Jan 12 05:41 collection-21-3147801643784858223.wt
-rw-------. 1 mongod mongod    4706304 Jan 12 09:02 collection-22--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-22--5305699207077892184.wt
-rw-------. 1 mongod mongod       4096 Jan 12 05:34 collection-2-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 collection-23-3147801643784858223.wt
-rw-------. 1 mongod mongod      53248 Jan 12 15:14 collection-23--5305699207077892184.wt
-rw-------. 1 mongod mongod   32006144 Jan 12 09:02 collection-24--1809642965555131340.wt
-rw-------. 1 mongod mongod      45056 Jan 12 15:14 collection-2--4569173258061928719.wt
-rw-------. 1 mongod mongod      20480 Jan 11 11:43 collection-2-4663825045788152862.wt
-rw-------. 1 mongod mongod   71290880 Jan 12 08:24 collection-2--5305699207077892184.wt
-rw-------. 1 mongod mongod      45056 Jan 12 05:41 collection-25-3147801643784858223.wt
-rw-------. 1 mongod mongod      77824 Jan 12 00:48 collection-2-6066076875358285443.wt
-rw-------. 1 mongod mongod  115519488 Jan 12 09:02 collection-26--1809642965555131340.wt
-rw-------. 1 mongod mongod      40960 Jan 12 05:34 collection-27-3147801643784858223.wt
-rw-------. 1 mongod mongod   11030528 Jan 12 06:31 collection-28--1809642965555131340.wt
-rw-------. 1 mongod mongod      40960 Jan 12 21:35 collection-2--9202003834816367794.wt
-rw-------. 1 mongod mongod      53248 Jan 12 05:34 collection-29-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-29--5305699207077892184.wt
-rw-------. 1 mongod mongod      69632 Jan 12 09:02 collection-30--1809642965555131340.wt
-rw-------. 1 mongod mongod      49152 Jan 12 05:34 collection-31-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-31--5305699207077892184.wt
-rw-------. 1 mongod mongod     376832 Jan 12 05:34 collection-33-3147801643784858223.wt
-rw-------. 1 mongod mongod     249856 Jan 12 09:02 collection-34--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-34--5305699207077892184.wt
-rw-------. 1 mongod mongod      45056 Jan 12 09:02 collection-35-3147801643784858223.wt
-rw-------. 1 mongod mongod  797519872 Jan 12 09:02 collection-36--1809642965555131340.wt
-rw-------. 1 mongod mongod   19816448 Jan 12 09:02 collection-39-3147801643784858223.wt
-rw-------. 1 mongod mongod 2715410432 Jan 12 09:02 collection-40--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 08:32 collection-41-3147801643784858223.wt
-rw-------. 1 mongod mongod 3723812864 Jan 12 06:31 collection-4--1809642965555131340.wt
-rw-------. 1 mongod mongod     131072 Jan 12 05:34 collection-4-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 08:32 collection-43-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 08:32 collection-45-3147801643784858223.wt
-rw-------. 1 mongod mongod  218435584 Jan 12 09:02 collection-46--1809642965555131340.wt
-rw-------. 1 mongod mongod     249856 Jan 12 09:02 collection-47-3147801643784858223.wt
-rw-------. 1 mongod mongod      24576 Jan 12 22:39 collection-4--9202003834816367794.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 collection-49-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-49--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-50--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 collection-51-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-51--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-52--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-52--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 collection-53-3147801643784858223.wt
-rw-------. 1 mongod mongod     462848 Jan 12 09:02 collection-5--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 collection-55-3147801643784858223.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 collection-57-3147801643784858223.wt
-rw-------. 1 mongod mongod       4096 Jan 12 09:02 collection-57--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-58--5305699207077892184.wt
-rw-------. 1 mongod mongod      61440 Jan 12 09:02 collection-59--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 collection-6--1809642965555131340.wt
-rw-------. 1 mongod mongod      73728 Jan 11 11:44 collection-6-2938523890601203458.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-65--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 collection-66--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-67--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 collection-73--5305699207077892184.wt
-rw-------. 1 mongod mongod       4096 Jan 12 09:02 collection-75--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 collection-76--5305699207077892184.wt
-rw-------. 1 mongod mongod   18849792 Jan 12 09:02 collection-8--1809642965555131340.wt
-rw-------. 1 mongod mongod  233172992 Jan 11 11:44 collection-8-2938523890601203458.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 collection-83--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-84--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 collection-89--5305699207077892184.wt
-rw-------. 1 mongod mongod      61440 Jan 12 05:34 collection-9-3147801643784858223.wt
-rw-------. 1 mongod mongod    3988819 Jan 11 11:44 cpu_stats.txt
drwx------. 2 mongod mongod       4096 Jan 12 23:46 diagnostic.data
-rw-------. 1 mongod mongod   26472448 Jan 11 11:44 index-10-2938523890601203458.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-10-3147801643784858223.wt
-rw-------. 1 mongod mongod      81920 Jan 12 09:02 index-11--1809642965555131340.wt
-rw-------. 1 mongod mongod      40960 Jan 12 09:02 index-1--1245733199008363699.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-1--1809642965555131340.wt
-rw-------. 1 mongod mongod   26210304 Jan 11 11:44 index-12-2938523890601203458.wt
-rw-------. 1 mongod mongod      45056 Jan 12 09:03 index-12-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:44 index-1-2938523890601203458.wt
-rw-------. 1 mongod mongod    2162688 Jan 12 08:55 index-13--1809642965555131340.wt
-rw-------. 1 mongod mongod    1466368 Jan 12 08:55 index-14--1809642965555131340.wt
-rw-------. 1 mongod mongod   52875264 Jan 11 11:44 index-14-2938523890601203458.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-14-3147801643784858223.wt
-rw-------. 1 mongod mongod     126976 Jan 12 09:02 index-14--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:44 index-1-4663825045788152862.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-1--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-1-6066076875358285443.wt
-rw-------. 1 mongod mongod      61440 Jan 12 16:32 index-16-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 04:49 index-16--5305699207077892184.wt
-rw-------. 1 mongod mongod    1044480 Jan 12 09:02 index-17--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-17--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:40 index-18-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:44 index-1-9092172278719928609.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-19--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:49 index-1--9202003834816367794.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:40 index-20-3147801643784858223.wt
-rw-------. 1 mongod mongod     364544 Jan 12 09:02 index-21--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 15:14 index-21--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:41 index-22-3147801643784858223.wt
-rw-------. 1 mongod mongod      69632 Jan 12 09:02 index-23--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-24-3147801643784858223.wt
-rw-------. 1 mongod mongod     294912 Jan 12 09:02 index-25--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:41 index-26-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-26--5305699207077892184.wt
-rw-------. 1 mongod mongod     618496 Jan 12 09:02 index-27--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 15:14 index-27--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-28-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:49 index-2-9092172278719928609.wt
-rw-------. 1 mongod mongod     360448 Jan 12 09:02 index-29--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-30-3147801643784858223.wt
-rw-------. 1 mongod mongod      45056 Jan 12 09:02 index-31--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 15:14 index-3--1245733199008363699.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-32--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-32-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-32--5305699207077892184.wt
-rw-------. 1 mongod mongod       4096 Jan 12 05:34 index-3-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-34-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 15:14 index-3--4569173258061928719.wt
-rw-------. 1 mongod mongod      20480 Jan 11 11:44 index-3-4663825045788152862.wt
-rw-------. 1 mongod mongod     102400 Jan 12 09:02 index-35--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-3-6066076875358285443.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-36-3147801643784858223.wt
-rw-------. 1 mongod mongod   17780736 Jan 12 09:02 index-37--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-37--5305699207077892184.wt
-rw-------. 1 mongod mongod   11055104 Jan 12 09:02 index-38--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-38--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 21:35 index-3--9202003834816367794.wt
-rw-------. 1 mongod mongod     581632 Jan 12 09:02 index-40-3147801643784858223.wt
-rw-------. 1 mongod mongod   37298176 Jan 12 09:02 index-41--1809642965555131340.wt
-rw-------. 1 mongod mongod   15314944 Jan 12 09:02 index-42--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 08:32 index-42-3147801643784858223.wt
-rw-------. 1 mongod mongod   15351808 Jan 12 09:02 index-44--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 08:32 index-44-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 08:32 index-46-3147801643784858223.wt
-rw-------. 1 mongod mongod    1646592 Jan 12 09:02 index-47--1809642965555131340.wt
-rw-------. 1 mongod mongod     761856 Jan 12 09:02 index-48--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-48-3147801643784858223.wt
-rw-------. 1 mongod mongod     761856 Jan 12 09:02 index-50--1809642965555131340.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 index-50-3147801643784858223.wt
-rw-------. 1 mongod mongod   14553088 Jan 12 09:02 index-5--1809642965555131340.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 index-52-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-5-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-53--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-53--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 index-54-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-54--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-55--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 08:32 index-56-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-56--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-58-3147801643784858223.wt
-rw-------. 1 mongod mongod      24576 Jan 12 22:39 index-5--9202003834816367794.wt
-rw-------. 1 mongod mongod       4096 Jan 12 09:02 index-61--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-62--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 05:34 index-6-3147801643784858223.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-63--5305699207077892184.wt
-rw-------. 1 mongod mongod     372736 Jan 12 08:24 index-6--5305699207077892184.wt
-rw-------. 1 mongod mongod      12288 Jan 12 22:41 index-6--9202003834816367794.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-69--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-70--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-71--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-7--1809642965555131340.wt
-rw-------. 1 mongod mongod      36864 Jan 11 11:44 index-7-2938523890601203458.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-77--5305699207077892184.wt
-rw-------. 1 mongod mongod       4096 Jan 12 09:02 index-79--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-80--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-87--5305699207077892184.wt
-rw-------. 1 mongod mongod      20480 Jan 12 09:02 index-88--5305699207077892184.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-90--5305699207077892184.wt
-rw-------. 1 mongod mongod     135168 Jan 12 09:02 index-9--1809642965555131340.wt
-rw-------. 1 mongod mongod   58232832 Jan 11 11:44 index-9-2938523890601203458.wt
-rw-------. 1 mongod mongod      36864 Jan 12 09:02 index-9--5305699207077892184.wt
drwx------. 2 mongod mongod       4096 Jan 11 11:49 journal
-rw-------. 1 mongod mongod      53248 Jan 11 11:49 _mdb_catalog.wt
-rw-------. 1 mongod mongod          6 Jan 11 11:49 mongod.lock
-rw-------. 1 mongod mongod      53248 Jan 12 22:40 sizeStorer.wt
-rw-------. 1 mongod mongod        114 Jan 11 11:44 storage.bson
-rw-------. 1 mongod mongod         46 Jan 11 11:44 WiredTiger
-rw-------. 1 mongod mongod       4096 Jan 11 11:49 WiredTigerLAS.wt
-rw-------. 1 mongod mongod         21 Jan 11 11:44 WiredTiger.lock
-rw-------. 1 mongod mongod       1269 Jan 12 22:42 WiredTiger.turtle
-rw-------. 1 mongod mongod     466944 Jan 12 22:42 WiredTiger.wt

[Assistant]
Text:You will need to share the content of the log file because everything looks fine.More commands to run:
Code:cat /data/mongoDB/mongod.pid
ps -aef | grep [m]ongod
ss -tlnp
ls -l /tmp/mongo*

[Assistant]
Text:mongod -f /etc/mongod.conf
systemctl start mongod.sericeYou have to do one or the other.  Not both.  If you start mongod once manually, it won’t start as a service because it is already running.
Code:

[Assistant]
Text:I’ll try not to add noise to the post, but normally running from CLI with the --fork option, and the same yaml configuration file (commenting # the fork) throws some good information to start troubleshooting.Also, including the logs after starting the service, even though you believe it’s not relevant, it may be useful. Because error status 1 is thrown by systemd but does not correspond to a mongod error afaik
Code:--fork#

[Assistant]
Text:Hi @Chinmaya_DasIs SELinux enabled?   If it is change the SELinux mode to permissive and try again.If you need SELinux then moving the directories around while not difficult become non-trivial.I think I have posted about it before or it may even be documented alrady.
Code:

[User]
Text:
Code:


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

[System] The following conversation has title: Client network socket disconnected before secure TLS connection was established and tags: ['node-js', 'atlas']

[User]
Text:I am using MongoClient in NodeJs to carry out Db operations, I am running into connection and db caching issues,
I’m getting the following error in my application -
error 1 -error 2-Following is my DB connection and closing code-** I call the client method while going any db operation like findOne, insertOne, etc
And closeDBConnection right before returning the API response.
Code:Error: Client network socket disconnected before secure TLS connection was established
    at connResetException (internal/errors.js:609:14)
    at TLSSocket.onConnectEnd (_tls_wrap.js:1557:19)
    at Object.onceWrapper (events.js:420:28)
    at TLSSocket.emit (events.js:326:22)
    at TLSSocket.EventEmitter.emit (domain.js:483:12)
    at endReadableNT (_stream_readable.js:1241:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  name: 'MongoNetworkError'
MongoServerSelectionError: Server selection timed out after 30000 ms
    at Timeout._onTimeout (/var/task/node_modules/mongodb/lib/core/sdam/topology.js:430:30)
    at listOnTimeout (internal/timers.js:554:17)
    at processTimers (internal/timers.js:497:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: 'atlas-3kud01-shard-0',
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map {
      'productioneuro-shard-00-00.vfau2.mongodb.net:27017' => [ServerDescription],
      'productioneuro-shard-00-01.vfau2.mongodb.net:27017' => [ServerDescription],
      'productioneuro-shard-00-02.vfau2.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: 30,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: 9
  }
}
clientcloseDBConnectionimport { MongoClient, Db } from "mongodb";

let cachedDb: Db = null;
let mongoClient: MongoClient = null;

export const client = async (): Promise<Db> => {
  if (cachedDb && await mongoClient.isConnected()) {
    console.info("cached db connection established");
    return cachedDb;
  }

  mongoClient = new MongoClient('db URL here', {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    connectTimeoutMS: 90000,
    poolSize: 10
  });
  try {
    await mongoClient.connect();

    if (await !mongoClient.isConnected()) {
      await mongoClient.connect(err => {
        if (err) {
          console.error("Error : ", err);
          throw new Error(`Unable to connect MongoDb Client, Reason: ${err}`
          );
        }
      });
    }

    cachedDb = await mongoClient.db(await "DB name here");
    console.info("db connection established");
    return cachedDb;
  } catch (error) {
    console.error("Error in connecting to DB => ", error);
    throw error;
  }
};

export const closeDBConnection = async () => {
  try {
    if( mongoClient != null ){
      await mongoClient.close();
      mongoClient = null;
      cachedDb = null;

      console.log("db connection closed");
      return true;
    }
  } catch (error) {
    console.log("Error in closeDBConnection => ", error);
    return false;
  }
};

[Assistant]
Text:Hi @Aniruddha_Raje.
Can you please confirm that you have added your IP address to IP Access List in Network Access tab of Atlas menu?
Also, please make sure that you are not using any firewall.
Once that is done, please try to connect again.In case you have any doubts, please feel free to reach out to us.Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer
Code:


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

[System] The following conversation has title: Querying with Object ID vs Querying with array and tags: ['queries', 'data-modeling', 'python']

[User]
Text:I am migrating from another service and changing structure of the database a bit. I already have unique IDs attached to every data group I have and I couldn’t decide if I use this IDs as an ObjectID or inside the document as an array.Would setting them as ObjectID help with querying performance?Thanks a lot in advance.
Code:

[Assistant]
Text:Hi,ObjectId is a special data format of 12-byte that consists of:You should check if your current unique IDs are compatible with this. One advantage of having ObjectId is that you can also do the sort based on it, since it have creation date info inside it.I would recommend to go with ObjectId if you don’t have to do bigger code refactor because of the change.
Code:ObjectIdObjectIdsort

[User]
Text:So I can’t just set a random 9 (or 10) digit number as the object ID? Do I get it right?Thanks a lot for your response.
Code:

[Assistant]
Text:Hi,You don’t have to specify anything. If you don’t specify _id explicitly, Mongo will automatically set it as unique ObjectId.
Code:_id

[Assistant]
Text:You may use anything value for the field _id, a number, a date or a string, even an object but not an array.  The only restriction is that is has to be unique within the collection.  It has to be unique because all collections comes with a default index on the _id field.  You may even have different type within the same collection.Here are some example:So, yes setting you existing unique IDs as the _id will help performance because you get an index by default.You probably cannot convert your unique (9 to 10 random number) IDs to an ObjectId() because it is special as special as explained by @NeNaD but you may certainly use them as is for the value of the _id field.
Code:mongosh test> c.find()
[
  { _id: 369 },
  { _id: '369' },
  { _id: ISODate("2022-04-09T18:12:37.203Z") },
  { _id: { user: 'steevej', domain: 'gmail.com' } },
  { _id: ObjectId("6251cdb3347f73b0e4852b62") }
]


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

[System] The following conversation has title: Failed schema validation after insert with sdk's becuase of null value and tags: ['atlas-device-sync', 'schema-validation']

[User]
Text:hi,
After I insert a new Realm-Object via SDK (Swift or Java) that contains a null value I run into a schema validation error:2	Invalid Type	InvalidTypeError	taskIdtaskId is a optional attribute defined like:how can i save a null value?thank you
Code:"taskId": {
      "bsonType": "objectId"
 }

[User]
Text:In the Documentation I found this:Optional properties may contain a null value or be entirely omitted from an object. By default, all properties are required unless explicitly marked as optional.so i modify my schema to:But I still get the InvlidTypeError because of the null value…
Code:"taskId": {
   "bsonType": "objectId",
   "optional": true
 }

[User]
Text:here my swift object model:class EventT: Object {
@objc dynamic var _id: ObjectId = ObjectId.generate()
@objc dynamic var taskId: ObjectId?
}
Code:

[Assistant]
Text:Hi @rouuuge, have you defined a primary key for the Object (I assume you’d want something like:In your schema, check that taskId isn’t included in the required section. e.g., this would prevent you having it set to nil:
Code:override static func primaryKey() -> String? {
    return "_id"
}
taskIdrequirednil"required": [
        "_id",
        "taskId"
      ],

[User]
Text:hi @Andrew_Morgan, yes I defined my primary key and the taskId is not ind the required section. Sorry for the incomplete example!Also the synchronization works. The only thing is the validation from the object after I inserted it via sdk:Bildschirmfoto 2021-03-17 um 23.40.05697×135 13.1 KBbecause of the null type here:Bildschirmfoto 2021-03-17 um 23.40.36823×24 1.9 KBSo far I ignored that because the sync between mobile works. But now I started to implement a WebApp with realm-web. This works until I try to update a object that was created by a IOS-Device via the WebApp.If I want to update just one field from the object with the update $set:I get the same error like on the mongodb-validation step:could not validate document: note: Invalid type. Expected: undefined, given: null taskId: Invalid type. Expected: undefined, given: nullthanks for looking into this
Code:taskIdrequiredrealm-webupdate$set"update": {
  "$set": {
    "state": {
      "$numberInt": "1"
     }
 ...

[Assistant]
Text:@rouuuge Thanks for the extra info.I’ve recreated the issue and have raised the question with the engineering team. I’ll let you know when I get a response.
Code:

[User]
Text:Thank you @Andrew_Morgan!I just checked the android SKD (java). There is the same problem as with the swift SDK.
Code:

[Assistant]
Text:Thanks for confirming. I suspect that the issue will be with the translator component in the backend that maps to Atlas documents
Code:

[User]
Text:hi @Andrew_Morgan do you have any updates about this?
Code:

[Assistant]
Text:Hi @rouuuge it appears that we’re running up against the differences between what’s supported by Objects and JSON Schema. Something to try (to allow you to modify documents in Atlas) is to click on the “Advanced Mode” button on the schema page in the Realm UI and set apply_when to false.
Code:apply_whenfalse

[User]
Text:hi,to allow you to modify documents in Atlasmy problem is not that i cant modify documents in Atlas. Or maybe I missunderstand you. This post I posted on february describe the problem maybe a bit more clearer:
Code:

[Assistant]
Text:hi @rouuuge,
The schema that you see in the Realm UI is used for a number of things – GraphQL API, Atlas document validations, and Realm Sync. I’m assuming that the part you care about is Realm Sync. My suggested workaround should stop the schema being used for Atlas document validation, and so (after the change) the schema shouldn’t prevent you from making changes to the Atlas data.
Code:

[Assistant]
Text:Hi @Andrew_Morgan
Any updates on this? I believe I am facing the same underlying issue.
Code:

[Assistant]
Text:Could you share your iOS Object class definition plus the Realm schema? I’m travelling this week but I’ll try to reproduce the issue.
Code:

[Assistant]
Text:Safe travels.
There you go, I replied to the original post
Code:

[Assistant]
Text:Hi @Georges_Jamous I’m afraid that I haven’t had chance to recreate this. Have you tried setting apply_when to false in the schema Advanced Mode?
Code:apply_whenfalse

[User]
Text:hi @Andrew_Morgan
on Mar 18 you wrote:I’ve recreated the issue and have raised the question with the engineering team. I’ll let you know when I get a response.What was the response? It looks that you could recreated my example? If setting apply_when really the only solution could you describe bit more where to insert that rule? (btw im Using realm Sync)thank you
Code:

[Assistant]
Text:Hi @Andrew_MorganI am not using GraphQL, just using iOS Sync. Where would I be able to change this?I ran into the same issue today, do you have any update from the team?I seems that the root cause is that no matter what the field type is, using a function to update it, it must have a value.
Non existent key, key set to null or key set to undefined does not work.
For my optional string schema, I had to pass an empty string ""
Code:""

[Assistant]
Text:I also attempted to update an existing object in the Database that was synced from iOS Client containing an non-existent value for an optional key.
In the Collection that value was Null.it failed stating the the value that was already non existent (NULL in record) needed to be Undefined. But it was Null. (again, the NULL value was set by the sync client form the SDK or Realm server)it looks like the validation mechanism that runs when updating a value is different that the one during a sync operation in the backend
Code:await collection.updateOne(
            { _id: ... },
            { $set: { parentId: newID }},
            { session });

// the object I am updating here contains a key
// { name: null }
Expected: undefined, given: null


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

[System] The following conversation has title: MongoServerSelectionError: connect ECONNREFUSED ::1:27017 and tags: ['node-js', 'compass']

[User]
Text:Hello all,New to Mongo so I’ll do my best to provide as many details as possible to solve my issue. I’ve searched this forum but nothing presented any solutions.Installed MongoDB Community 5.0.6 via the tarball to the location of /usr/local/mongodb on an Intel Mac running OS Big Sur 11.6.5
Launched the db with mongod --dbpath ~/data/dbConnecting to db with mongo shell and MongoDB Compass worked flawlessly. I can connect to dbs, create dbs/collections, modify data, etc.My issue is trying to connect using the official mongodb 4.5.0 node package. I’ve stripped down the code only trying to connect() with code taken directly from Mongo’s official YouTube demo.Running the code returns the following error:I’ve not modified any configuration options other than using the --dbpath as using /data/db was not allowed. I’ve tried rolling back the node package to version 4.4.1 as well as trying MongoDB version 4.4 but no luck there either.Thanks in advance for any help,
Jim
Code:/usr/local/mongodbmongod --dbpath ~/data/dbconst { MongoClient } = require('mongodb')

async function main() {

  const url = 'mongodb://localhost:27017'

  const client = new MongoClient(url)

  try {
    await client.connect()
  } catch (e) {
    console.error(e)
  } finally {
    await client.close()
  }
}

main().catch(console.error)
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (/Users/jimhall/blog-backend/node_modules/mongodb/lib/sdam/topology.js:318:38)
    at listOnTimeout (node:internal/timers:568:17)
    at processTimers (node:internal/timers:510:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

[Assistant]
Text:Try with 127.0.0.1:27017 rather than localhost:27017.Looks like localhost is not resolved correctly.
Code:

[User]
Text:Try with 127.0.0.1:27017 rather than localhost:27017 .I’ve tried that multiple times, swapping the loopback ip for localhost, it never worked. But for some reason now that you said it, it worked. Almost didn’t try again because of that. Wonder why localhost is not recognized. It works fine using it elsewhere.
Code:

[Assistant]
Text:May be it is only defined for IPv6.Take a peek in /etc/hosts.
Code:


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

[System] The following conversation has title: How to compare two documents and tags: ['aggregation', 'queries']

[User]
Text:How do I compare the equality of two documents? Let’s say I have new data coming from a web form. In that form I have an external id that gets stored along with all the fields. So when data comes from the client, I do a query utilizing that external id, given that I have a match I would like to know if the rest of the values are equals or not, in other words, I’m comparing the entire document against each other, the one coming from the client and the one already in the database.I would like to know if Mongo itself has an operator ($eq, $lookup, etc) for comparing two documents.
Code:idid

[Assistant]
Text:I would like to know if Mongo itself has an operator ($eq, $lookup, etc) for comparing two documents.@redeemefy we don’t have a basic solution however the blog post “Comparing Subdocuments In MongoDB Expressions” offers a solution that may be suitable for your use case.
Code:

[Assistant]
Text:Assuming JavaScript you could use JSON.stringify() to compare 2 objects.With Java, you could use toJson() and do the same comparison.In python you may compare the dictionary directly.
Code:a = { "first" : "steeve" , "last" : "juneau" , "id" : "steevej" }
b = { "first" : "steeve" , "last" : "juneau" , "id" : "steevej" }
c = { "first" : "steeve" , "last" : "juneau" , "id" : "steeve" }
JSON.stringify(a) == JSON.stringify(b)
// will be true
JSON.stringify(a) == JSON.stringify(c)
// will be false

[User]
Text:I believe this approach is not going to work.Same properties and all properties with the same values but those properties in different order in the document returns false.
Code:const a = { a: 'test', b: 'sample' }
const b = { b: 'sample', a: 'test' }
JSON.stringify(a) == JSON.stringify(b) // false


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

[System] The following conversation has title: Error start mongodb centos7 and tags: ['installation']

[User]
Text:good morningI installed mongodb on a virtual machine with centos 7 operating system.
I followed the guide on the mongodb site
Install MongoDB Community Edition on Red Hat or CentOSWhen I run the command systemctl start mongod
gives me the following error
Job for mongod.service failed because a fatal signal was delivered to the control process. See “systemctl status mongod.service” and “journalctl -xe” for details.The following command systemctl status mongod.service returnswhile the journalctl -xethe folders for the data are/ var / lib / mongo (the data directory)
/ var / log / mongodb (the log directory)
and the permissions are correctWhat could be causing the problem? How can I solve?Thanks Alessio
Code:  Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: failed (Result: signal) since Wed 2022-03-30 13:58:28 CEST; 5min ago
     Docs: https://docs.mongodb.org/manual
  Process: 52061 ExecStart = / usr / bin / mongod $ OPTIONS (code = killed, signal = ILL)
  Process: 52058 ExecStartPre = / usr / bin / chmod 0755 / var / run / mongodb (code = exited, status = 0 / SUCCESS)
  Process: 52055 ExecStartPre = / usr / bin / chown mongod: mongod / var / run / mongodb (code = exited, status = 0 / SUCCESS)
  Process: 52053 ExecStartPre = / usr / bin / mkdir -p / var / run / mongodb (code = exited, status = 0 / SUCCESS)

Tue 30 13:58:28 mongodba systemd [1]: Starting MongoDB Database Server ...
Tue 30 13:58:28 mongodba systemd [1]: mongod.service: control process exited, code = killed status = 4
Tue 30 13:58:28 mongodba systemd [1]: Failed to start MongoDB Database Server.
Tue 30 13:58:28 mongodba systemd [1]: Unit mongod.service entered failed state.
Tue 30 13:58:28 mongodba systemd [1]: mongod.service failed.
Tue 30 13:58:12 mongodba crond [51736]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 25% if used.)
Tue 30 13:58:12 mongodba crond [51736]: (CRON) INFO (running with inotify support)
Tue 30 13:58:12 mongodba crond [51736]: (CRON) INFO (@reboot jobs will be run at computer's startup.)
Tue 30 13:58:12 mongodba systemd [1]: Reloading.
Tue 30 13:58:12 mongodba systemd [1]: Reloading.
Tue 30 13:58:12 mongodba systemd [1]: Stopped Dynamic System Tuning Daemon.
- Subject: Unit tuned.service has finished shutting down
- Defined-By: systemd
- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-
- Unit tuned.service has finished shutting down.
Tue 30 13:58:12 mongodba systemd [1]: Starting Dynamic System Tuning Daemon ...
- Subject: Unit tuned.service has begun start-up
- Defined-By: systemd
- Support: http:// lists.freedesktop . org /mailman/listinfo/systemd-devel
-
- Unit tuned.service has begun starting up.
Tue 30 13:58:13 mongodba systemd [1]: Started Dynamic System Tuning Daemon.
- Subject: Unit tuned.service has finished start-up
- Defined-By: systemd
- Support: http:/ / lists. freedesktop .org /mailman/listinfo/systemd-devel
-
- Unit tuned.service has finished starting up.
-
- The start-up result is done.
Mar 30 13:58:28 mongodba polkitd [51710]: Registered Authentication Agent for unix-process: 52047: 9623813 (system bus name: 1.100 [/ usr / bin / pkttyagent --notify-fd 5 --fallback], object path / org / freedesktop / P
Tue 30 13:58:28 mongodba systemd [1]: Starting MongoDB Database Server ...
- Subject: Unit mongod.service has begun start-up
- Defined-By: systemd
- Support: http: // lists .freedesktop . org/mailman/listinfo/systemd-devel
-
- Unit mongod.service has begun starting up.
Mar 30 13:58:28 mongodba kernel: traps: mongod [52061] trap invalid opcode ip: 55e8bac4e48a sp: 7ffd62f3cf30 error: 0 in mongod [55e8b6c5d000 + 513a000]
Tue 30 13:58:28 mongodba systemd [1]: mongod.service: control process exited, code = killed status = 4
Tue 30 13:58:28 mongodba systemd [1]: Failed to start MongoDB Database Server.
- Subject: Unit mongod.service has failed
- Defined-By: systemd
- Support: http: // lists .freedesktop .org/  mailman/listinfo/systemd-devel
-
- Unit mongod.service has failed.
-
- The result is failed.
Tue 30 13:58:28 mongodba systemd [1]: Unit mongod.service entered failed state.
Tue 30 13:58:28 mongodba systemd [1]: mongod.service failed.
Tue 30 13:58:28 mongodba polkitd [51710]: Unregistered Authentication Agent for unix-process: 52047: 9623813 (system bus name: 1.100, object path / org / freedesktop / PolicyKit1 / AuthenticationAgent, local en_US.U
Tue 30 14:01:01 mongodba systemd [1]: Started Session 31 of user root.
- Subject: Unit session-31.scope has finished start-up
- Defined-By: systemd
- Support: http :// lists. freedesktop .org/mailman/listinfo/systemd-devel
-
- Unit session-31.scope has finished starting up.
-
- The start-up result is done.
Tue 30 14:01:01 mongodba CROND [52972]: (root) CMD (run-parts /etc/cron.hourly)
Tue 30 14:01:01 mongodba run-parts (/etc/cron.hourly) [52975]: starting 0anacron
Mar 30 14:01:01 mongodba run-parts (/etc/cron.hourly) [52981]: finished 0anacron

[Assistant]
Text:Your dir paths showing spaces?
Can you cd to your dirpath & logpath?
Are they existing with correct permissions and ownership
Code:

[User]
Text:the directory have spacescd /var/lib/
drwxr-xr-x  2 mongod  mongod    27 Mar 30 08:12 mongocd /var/log/
drwxr-xr-x  2 mongod mongod      24 Mar 28 15:02 mongodbdf -h
/dev/sdb        100G   33M  100G   1% /var/lib/mongomount
/dev/sdb on /var/lib/mongo type xfs (rw,relatime,attr2,inode64,noquota)cat /etc/passwd
mongod:x:997:996:mongod:/var/lib/mongo:/bin/falsethese are the characteristics of the configuration. if you need others to help me let me know
Code:

[Assistant]
Text:ILL is Illegal operation. This is likely due to using an incompatible CPU(old) with later versions of mongod.Check your CPU meets the requirements.x86_64MongoDB requires the following minimum x86_64 microarchitectures: [2]MongoDB 5.0 requires use of the AVX instruction set, available on select Intel and AMD processors.
Code:x86_64x86_64x86_64

[User]
Text:Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                8
On-line CPU(s) list:   0-7
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             4
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 23
Model name:            Intel(R) Xeon(R) CPU E5-2650 v4 @ 2.20GHz
Stepping:              6
CPU MHz:               2197.455
BogoMIPS:              4394.91
Hypervisor vendor:     VMware
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              30720K
NUMA node0 CPU(s):     0-7
Code:

[Assistant]
Text:VMware, check EVC mode too.
Code:

[User]
Text:I was unable to resolve. Are there any other ideas? Do you need more info?
Code:

[Assistant]
Text:What did you try?Provide the output of /proc/cpuinfo
Code:/proc/cpuinfo

[User]
Text:/proc/cpuinfoprocessor       : 7
vendor_id       : GenuineIntel
cpu family      : 6
model           : 23
model name      : Intel(R) Xeon(R) CPU E5-2650 v4 @ 2.20GHz
stepping        : 6
microcode       : 0xb000038
cpu MHz         : 2197.455
cache size      : 30720 KB
physical id     : 3
siblings        : 2
core id         : 1
cpu cores       : 2
apicid          : 7
initial apicid  : 7
fpu             : yes
fpu_exception   : yes
cpuid level     : 10
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx lm constant_tsc arch_perfmon nopl tsc_reliable nonstop_tsc eagerfpu pni ssse3 cx16 sse4_1 tsc_deadline_timer hypervisor lahf_lm ssbd ibrs ibpb stibp tsc_adjust arat spec_ctrl intel_stibp flush_l1d arch_capabilities
bogomips        : 4394.91
clflush size    : 64
cache_alignment : 64
address sizes   : 43 bits physical, 48 bits virtual
power management:
Code:/proc/cpuinfo

[Assistant]
Text:You’re missing AVX in the flags.The CPU does support them so you need to go back and look at the VMWare EVC modes.Alternatively go to mongo 4.4  or compile from source.
Code:


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

[System] The following conversation has title: Group by nested object and group items to array and tags: ['aggregation']

[User]
Text:I have an array like this:How do I convert to this:I know I can use $group operator but I only get _id field, please help me.
Code:[
    {
        name: "a",
        title: {
            title: "b",
            order: 1
        },
        group: "B"
    },
    {
        name: "b",
        title: {
            title: "b",
            order: 1
        },
        group: "B"
    },
    {
        name: "c",
        title: {
            title: "c",
            order: 2
        },
        group: "B"
    }
]
[
    {
        _id: "b",
        items: [
            {name: "a", group: "B"},
            {name: "b", group: "B"}
        ]
    },
    {
        _id: "c",
        items: [
            {name: "c", group: "B"}
        ]
    }
]

[Assistant]
Text:Hi,You can do it like this:Working exampleMongo playground: a simple sandbox to test and share MongoDB queries online
Code:db.collection.aggregate([
  {
    "$group": {
      "_id": "$title.title",
      "items": {
        "$addToSet": {
          "name": "$name",
          "group": "$group"
        }
      }
    }
  }
])


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

[System] The following conversation has title: How do I delete duplicate documents while unique index creation? and tags: ['indexes']

[User]
Text:I have an mongo instance (about 120GB RAM, 250GB SSD) running 4.0.10. I have a large collection of about 300M documents and I want to add an unique index on a collection. The index creation is quite slow, takes about 2 hours despite using most of the RAM and it is erroring out at 99% saying there is a dupe key.If I manually try to delete the key, it is taking hours. And seems dropDupes option was removed in recent version of Mongo.So, what do I do?Is there any way to make it log the _id of the duplicate key found?and what would be the fastest way to delete all the dupes?
Code:dropDupes_id

[Assistant]
Text:Hi @V_N_A,Wow honestly there is no easy way to find it in such a huge collection.I would say run an $group aggregation on that field and locate the value with more than 1 occurance.Try to run it on a secondary or even spin it on a temp port to isolate the env while locating.Once you find the value you can locate the _id or even add it in $group stage:Thanks
Pavel
Code:$group : { _id : "$FIELD" , count : { $sum : 1 } , id : { $push : "$$ROOT._id" }}

[User]
Text:Hey @Pavel_Duchovny, thank you for responding. I will give you some more context. A document in my collection looks like this:_id is the primary key. And I want to create the unique index on (client_id, message_id) fields. I tried to find the dupes, using aggregate framework, it was very slow. The console wouldn’t respond for hours.So, I created two indexes:this is my aggregate query, do you find anything odd in it?Why this is not using any of the indexes? Here is what it says when I do explain on it:
Code:{
        "_id" : ObjectId("6055ec15bfcb7198dffa042c"),
        "message_id" : "TeiaBrCXgGyaf6aTk",
        "client_id" : "april",
        // bunch of other fields
}
_id{
	"v" : 2,
	"key" : {
		"client_id" : 1,
		"message_id" : 1
	},
	"name" : "client_id_1_message_id_1",
	"ns" : "my_db.msgs"
},
{
	"v" : 2,
	"key" : {
		"_id" : 1,
		"client_id" : 1,
		"message_id" : 1
	},
	"name" : "_id_1_client_id_1_message_id_1",
	"ns" : "my_db.msgs"
},
db.msgs.aggregate([
  { $group: {
    _id: { "message_id": "$message_id", "client_id": "$client_id" },
    count: { $sum: 1 },
    id : { $push : "$$ROOT._id" }
  } },
  { $sort : { count : -1} },
  { $match: {
    count: { $gte: 2 }
  } },
], {
  allowDiskUse: true
});
{
	"stages" : [
		{
			"$cursor" : {
				"query" : {

				},
				"fields" : {
					"client_id" : 1,
					"message_id" : 1,
					"_id" : 1
				},
				"queryPlanner" : {
					"plannerVersion" : 1,
					"namespace" : "my_db.msgs",
					"indexFilterSet" : false,
					"parsedQuery" : {

					},
					"winningPlan" : {
						"stage" : "COLLSCAN",
						"direction" : "forward"
					},
					"rejectedPlans" : [ ]
				}
			}
		},
		{
			"$group" : {
				"_id" : {
					"message_id" : "$message_id",
					"client_id" : "$client_id"
				},
				"count" : {
					"$sum" : {
						"$const" : 1
					}
				},
				"id" : {
					"$push" : "$$ROOT._id"
				}
			}
		},
		{
			"$match" : {
				"count" : {
					"$gte" : 2
				}
			}
		},
		{
			"$sort" : {
				"sortKey" : {
					"count" : -1
				}
			}
		}
	],
	"serverInfo" : {
		"host" : "my_db",
		"port" : 27017,
		"version" : "4.0.23",
		"gitVersion" : "07c6611b38d2aacbdb1846b688db70b3273170fb"
	},
	"ok" : 1
}

[Assistant]
Text:Hi @V_N_A,It needs to do a full scan of 300M documents with this grouping, this is heavy and may take many hours…As suggested consider isolating it on a secondary stared on a temp port or take one of your backups and spin it on a dedicated host.There is no way to avoid the scanning here…
Code:

[User]
Text:As suggested consider isolating it on a secondary stared on a temp port or take one of your backups and spin it on a dedicated host.yup, doing this on a machine, on which I had inserted data with a dump. It’s not part of the replica set.Thanks for confirming @Pavel_Duchovny  I am running the aggregate query and I will wait till this is finished.I would really appreciate if you can have a look at this - What happens in case of a conflict during replication?
Code:

[User]
Text:Is there any way to speed up the background index creation? I am on Mongo 4.0.10 and the option of maxIndexBuildMemoryUsageMegabytes applies? cos in that page it says it applies to foreground builds, but on the Index Creation page - Index Build Operations on a Populated Collection — MongoDB Manual it is under background index creation section and does seem imply that it applies to background index creation as well
Code:

[Assistant]
Text:@V_N_A,Not really. Another option is to upgrade to 4.2+ with the improve index builds…Thanks.
Pavel
Code:


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

[System] The following conversation has title: Aggregate search filter for field being zero length array and tags: ['aggregation', 'queries', 'node-js', 'atlas-search']

[User]
Text:Hello mongo people!I’m trying to use the full text search feature with my Atlas collection. That seems to be working great. I also want the results to be limited to documents where a certain field - that is an array - is empty/has a zero length. I’ve been looking over the docs for the aggregate search pipeline but nothing seems to handle this that I can find.Previously, I was using the find() api like this:I feel like I should include this filter before the text search of other fields since it would greatly limit was needs… searched. What does that operation look like in an aggregate pipeline?Right now, I’m text searching like this:This is getting my a cursor of the result of docs where the title field does contain style, so that’s great! I was thinking this could be a compound operation since I also want to filter out the tags array field to empty ones but I might be mistaken there too.Any ideas on how to accomplish this query?
Code:find()collection.find({ tags: { $size: 0 } });
const cursor = collection.aggregate([
  {
    $search: {
      compound: {
        must: [
          {
            text: {
              query: 'style',
              path: ['title'],
            },
          },
        ],
      },
    },
  },
]);

[Assistant]
Text:Hi,You can add one Aggregation stage in the beginning of the Aggregation pipeline.Working example
Code:$match$expr$eq$sizetagsdb.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          0,
          {
            $size: "$tags"
          }
        ]
      }
    }
  }
])

[Assistant]
Text:add one Aggregation stage in the beginning of the Aggregation pipelineAccording to $search documentation $seach must be the first stage of the pipeline.To test the size of an array I prefer to use:The problem with $size is that it causes an error when the field tags does not exist withIt also causes an error when the field tags is not an array with:Since I am a big fan of the schema less nature of JSON and MongoDB, I prefer to use queries that accommodate that without error.All this being written, I have to admit that the following variant of $size also works without error.All this means that your filtering of empty tags array must be done after the $search.However, something that I have not tried, would be to set a partial index with your tags size as a condition and then specify the index to use in your $search.  Since the documents indexed will only be the one with $size:{$gt:0}, you kind of implicitly filter them out.
Code:{ "$match" : { "$tags.0" : { "$exists" : false } } }
MongoServerError: PlanExecutor error during aggregation :: caused by :: The argument to $size must be an array, but was of type: missing
MongoServerError: PlanExecutor error during aggregation :: caused by :: The argument to $size must be an array, but was of type: string
c.aggregate( { "$match" : { "tags" : { $size : 0 }} })

[User]
Text:According to $search documentation $seach must be the first stage of the pipeline.Yes, exactly. It was this requirement that kind of baffled me. I thought match or equals might be the answer, but wasn’t sure how they were shaped.Given that the text search has to be first, it does imply to me that all records will have their text fields inspected, and then whole swathes will be removed on the (in my mind) more simpler tags match. Is this not an inefficiency to mongo’s internals?
Code:


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

[System] The following conversation has title: Mongodb on Ubuntu -' Main process exited, code=exited, status=1/FAILURE' and tags: ['installation', 'configuration', 'storage']

[User]
Text:Mongo has suddenly stopped working, so I am trying to restart it I’ am getting again and again though errors like the below:I have revised the mongod.conf file, which is located in /etc and includes the below:Also the mongod.service located in /lib/systemd/system:I have also changed ownership using the below commands according to this post:I have checked the folders and removed .lock files from /var/lib/mongodb/ which now looks like below:According to a previous post I had once enabled wiredTiger engine from mongod.conf but have now changed it back to the .conf shared above. Should I remove these files as well from this directory?Finally, I have also checked the firewall for this port I am trying to use, it seems active. Have no idea what I should fix I have read lots of related posts but haven’t done yet…
Code: mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Τρι 2022-03-22 12:19:53 EET; 3h 46min ago
     Docs: https://docs.mongodb.org/manual
  Process: 27559 ExecStart=/usr/bin/mongod --auth --config /etc/mongod.conf (code=exited, status=1/FAILURE)
 Main PID: 27559 (code=exited, status=1/FAILURE)

systemd[1]: Started MongoDB Database Server.
systemd[1]: mongod.service: Main process exited, code=exited, status=1/FAILURE
systemd[1]: mongod.service: Unit entered failed state.
systemd[1]: mongod.service: Failed with result 'exit-code'.
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
# engine: wiredTiger
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 23654
  bindIp: 0.0.0.0

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target

[Service]
User=mongodb
Group=mongodb
EnvironmentFile=-/etc/default/mongod
ExecStart=/usr/bin/mongod --auth --config /etc/mongod.conf
PIDFile=/var/run/mongodb/mongod.pid
# file size
LimitFSIZE=infinity
# cpu time
LimitCPU=infinity
# virtual memory size
LimitAS=infinity
# open files
LimitNOFILE=64000
# processes/threads
LimitNPROC=64000
# locked memory
LimitMEMLOCK=infinity
# total threads (user+kernel)
TasksMax=infinity
TasksAccounting=false

# Recommended limits for for mongod as specified in
# http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings

[Install]
WantedBy=multi-user.target
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
sudo chown mongodb:mongodb /tmp/mongodb-23654.sock
sudo chown -R mongodb:mongodb /var/log/mongodb
 /var/lib/mongodb$ ls
    collection-0-2356690320700739995.wt   collection-2-2356690320700739995.wt  collection-8-5563536140699528517.wt  index-15-5563536140699528517.wt  index-5-5563536140699528517.wt  _mdb_catalog.wt    WiredTiger.wt
    collection-0-5563536140699528517.wt   collection-2-5563536140699528517.wt  diagnostic.data                      index-1-5563536140699528517.wt   index-6-2356690320700739995.wt  sizeStorer.wt
    collection-10-5563536140699528517.wt  collection-4-2356690320700739995.wt  index-10-2356690320700739995.wt      index-21-5563536140699528517.wt  index-7-5563536140699528517.wt  storage.bson
    collection-12-5563536140699528517.wt  collection-4-5563536140699528517.wt  index-11-5563536140699528517.wt      index-3-2356690320700739995.wt   index-9-2356690320700739995.wt  WiredTiger
    collection-14-5563536140699528517.wt  collection-6-5563536140699528517.wt  index-1-2356690320700739995.wt       index-3-5563536140699528517.wt   index-9-5563536140699528517.wt  WiredTigerLAS.wt
    collection-20-5563536140699528517.wt  collection-8-2356690320700739995.wt  index-13-5563536140699528517.wt      index-5-2356690320700739995.wt   journal                         WiredTiger.turtle

[Assistant]
Text:What is in the log file?What MongoDB version.
What OS, OS Version.
Code:

[User]
Text:The OS is  Ubuntu16.04.7 LTS
Mongo db v4.2.0
Unfortunately the file /var/log/mongodb/mongod.log only includes logs two days ago, although I have just tried to start mongod again, I have also looked as syslog but nothing is in there too.
Code:

[Assistant]
Text:Is PIDfile matching in services file and mongod.cfg
Why to chmod temp sock files
Looks like you started mongod earlier on port 27017 and now on new port
Try to move these *.sock files and see if it comes up
Code:

[User]
Text:You mean to remove both mongodb-23654.sock and mongodb-27017.sock?Well the 27017 should have been created once I have changed for a while the mongod.confThis kind of suggestions
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
were posted along with other suggested solutions in StackOverflow actually…
Code:> sudo rm /tmp/mongodb-23654.sock
> sudo rm /tmp/mongodb-27017.sock
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

[Assistant]
Text:other suggested solutions in StackOverflowNot always good./tmp/mongodb-27017.sockand similar are used by a running process and you must not temper them withsudo chown mongodb:mongodb /tmp/mongodb-27017.sockWhat you need to do is:
Code:ss -tlnp | grep 27017sudo /bin/rm -f /tmp/mongodb-27017.sock

[Assistant]
Text:As the logging is not providing error information. I would suggest running mongod manually at this point.This should error out. Given that nothing is appearingOtherwise you’re basically randomly changing/removing files/configuration without cause.
Code:sudo -u mongodb /usr/bin/mongod --auth --config /etc/mongod.conf

[User]
Text:I removed thistmp/mongodb-27017.sockThere is only 23654. sock available now, still it didn’t work.
Code:

[User]
Text:Nothing seems to be logged on the file/var/lib/mongodb/mongodb.logit is empty.
I  tried also adding quotes as per the official instructionsso the path to log files looks like
path: "/var/log/mongodb/mongod.log"still the same error…
Code:path: "/var/log/mongodb/mongod.log"

[Assistant]
Text:We need output of the following commandsIs the log file/var/lib/mongodb/mongodb.logor/var/log/mongodb/mongod.log
Code:ss -tlnp
ps -aef | grep [m]ongod
ls -l /tmp/mongodb-*

[User]
Text:apologies for the misunderstanding, the correct file is/var/log/mongodb/mongod.logResult ofss -tlnp
isand result of ls -l /tmp/mongodb-*
is
srwx------ 1 mongodb mongodb 0 Μάρ  23 17:24 /tmp/mongodb-23654.sockThe ps -aef | grep [m]ongod gave nothing.
Code:/var/log/mongodb/mongod.logss -tlnpState       Recv-Q Send-Q                                                                         Local Address:Port                                                                                Peer Address:Port
LISTEN      0      128                                                                                *:26603                                                                                *:*                   users:(("node",pid=2711,fd=23))
LISTEN      0      128                                                                                *:80                                                                                *:*
LISTEN      0      5                                                                                127.0.1.1:53                                                                                *:*
LISTEN      0      128                                                                                *:22                                                                                *:*
LISTEN      0      5                                                                                127.0.0.1:631                                                                                *:*
LISTEN      0      128                                                                                *:3000                                                                                *:*                   users:(("node",pid=2420,fd=23))
LISTEN      0      128                                                                                127.0.0.1:33980                                                                                *:*                   users:(("node",pid=2711,fd=22))
LISTEN      0      128                                                                                :::80                                                                                :::*
LISTEN      0      128                                                                                :::22                                                                                :::*
LISTEN      0      5                                                                                ::1:631                                                                                :::*
ls -l /tmp/mongodb-*srwx------ 1 mongodb mongodb 0 Μάρ  23 17:24 /tmp/mongodb-23654.sockps -aef | grep [m]ongod

[Assistant]
Text:Okay.Now remove /tmp/mongodb-… withNow manually start withsudo -u mongodb /usr/bin/mongod --auth --config /etc/mongod.confand post a screenshot of doing the above.  Also post the content of/var/log/mongodb/mongod.log
Code:sudo /bin/rm -f /tmp/mongodb-23654.sock
sudo -u mongodb /usr/bin/mongod --auth --config /etc/mongod.conf

[User]
Text:It still does not work   and the /var/log/mongodb/mongod.log seems empty.I suppose the logs are saved somewhere else so tried to find where with the below, but I am not sure if it correctly used:grep -r 'mongod.service: Main process exited, code=exited, status=1/FAILURE' *
Code:/var/log/mongodb/mongod.logsudo -u mongodb /usr/bin/mongod --auth --config /etc/mongod.conf
sudo vim /var/log/mongodb/mongod.log
sudo -u mongodb /usr/bin/mongod --auth --config /etc/mongod.conf
sudo systemctl status mongod
● mongod.service - MongoDB Database Server
>    Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
>    Active: failed (Result: exit-code) since Τετ 2022-03-23 20:49:30 EET; 2min 56s ago
>      Docs: https://docs.mongodb.org/manual
>   Process: 27417 ExecStart=/usr/bin/mongod --auth --config /etc/mongod.conf (code=exited, status=1/FAILURE)
>  Main PID: 27417 (code=exited, status=1/FAILURE)
>
 systemd[1]: Started MongoDB Database Server.
systemd[1]: mongod.service: Main process exited, code=exited, status=1/FAILURE
systemd[1]: mongod.service: Unit entered failed state.
systemd[1]: mongod.service: Failed with result 'exit-code'.
grep -r 'mongod.service: Main process exited, code=exited, status=1/FAILURE' *

[Assistant]
Text:Please show screenshot of the manual run
Did it complete successfully?
Can you run mongod as normal user on a different port,dbpath,logpath(not using your config file)
Code:

[User]
Text:The results when running the command you suggested:
image869×164 8.18 KB

Code:

[User]
Text:If I just try to mongod I get the below:
image1398×291 10.8 KB

Code:mongod

[Assistant]
Text:When you run mongod without any parameters it will try to start it on default port 27017 and default dirpath /data/db
Do you have this dir existing?I asked you to run on different dbpath,logpath,port like this to rule out any issues with dirs
Something like belowMongod --dbpath yourhomedir --logpath yourhomedir/mongod.log --port 29000 --forkOnce your mongod is up you can connect as
Mongo --port 29000
Code:

[User]
Text:The dir /data/db does exist

image929×309 9.11 KB

Code:/data/db

[User]
Text:Anyway I run thismongod --dbpath /var/lib/mongodb --logpath /var/log/mongodb/mongod.log --port 29000 --forkand get the below

image1895×134 8.02 KB

Code:


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

[System] The following conversation has title: Can I update a schema? and tags: ['data-modeling']

[User]
Text:Once a schema is created, is it possible to update it?For example, can I change the type from “string” to “enum:[]”
Code:

[Assistant]
Text:Depending on how you set up your schema you might have to shuffle data around, e.g., create a new collection and move the data over from the old collection, but it’s not rocket science.
Code:

[User]
Text:I see.To be clear then, there is no database command to db.updateScheme()^^ nothing like this?Id have to recreate and move the data?
Code:db.updateScheme()

[Assistant]
Text:Welcome to the MongoDB Community @Kevin_Izevbigie!Collections in MongoDB do not have a fixed schema, or requirement for all documents in a collection to have the same schema. You can definitely add or remove fields, change field types, or update JSON Schema validation without recreating a collection. The only top of mind exceptions would be changing an immutable field like _id  or changing a document’s shard key value in MongoDB server versions older than 4.2.Can you provide more information what you are referring to as schema? Do you mean JSON schema validation (which is enforced when documents are inserted or updated) or perhaps schema declared in an Object-Document Mapper (ODM) like Mongoose? What MongoDB driver and version are you using?Regards,
Stennie
Code:_id

[Assistant]
Text:Do you mean JSON schema validationThat’s how I was interpreting the question, @Stennie_X … maybe I jumped too quickly to a conclusion.
Code:

[User]
Text:You can definitely add or remove fields, change field types, or update JSON Schema validation without recreating a collection.Hi Both – this line is what I was talking about. When a Collection has been created and I defined a schema, how do I change a field type or remove a field? Or, most importantly, update the JSON schema validation rule set that I defined previously.ThanksK
Code:

[Assistant]
Text:Hi @Kevin_Izevbigie,Borrowing from discussion on a similar question in the context of the Node.js driver (How to use MongoDB for nodejs to modify the schema of an existing collection？ - #2 by Stennie):The essential step is:Once a collection has been created, use the  collMod command  to modify the validator for a collection.… and a handy hint for previewing the effects of a schema validation change:Note: the  $jsonSchema query operator  is also useful to test schema validation changes against existing documents. For an example using the mongo shell, see: How to find all invalid document based on jsonSchema validator? .Lastly, schema validation in MongoDB 5.0+ has improved error messages that will help you understand why a document fails schema validation: Improved Error Messages for Schema Validation in MongoDB 5.0 | MongoDB.If you happen to be using an older version of MongoDB server or would be like to validate earlier in your application logic (eg frontend or application code), you should be able to find a JSON Schema Validator library or package in your preferred implementation language. MongoDB’s JSON Schema implementation adds the bsonType keyword and has a few omissions, but should be straightforward to add if not already supported by your chosen validation package.Regards,
Stennie
Code:collModvalidator$jsonSchemamongobsonType