MongoDB

133

Solutions

246

Contributors

MongoDB (from humongous) is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. MongoDB is developed by MongoDB Inc. and is free and open-source, published under a combination of the GNU Affero General Public License and the Apache License.

Share tech news, updates, or what's on your mind.

Sign up to Post

I know there's a ton of questions around date/time storage and formatting, but I'm struggling to get the right approach. My app is a Node.js app with Express using mongoose with a MongoDB backend. I'm using moment.js to format my date/times.

The schema in question looks like:

const stateSchema = new mongoose.Schema({
  changed: {
    type: Date,
    default: new Date()
  }
});

Open in new window

Based on the docs, I was expecting the date to be stored in UTC by default, but instead I see this:
changed: 2018-08-15 17:26:14.499

Open in new window

I'm displaying the date/time with something like (pug):

p= `Changed: ${moment(state.changed).format('MMMM Do YYYY, h:mm:ss a')}`

Open in new window

On localhost, the app shows "August 15th 2018, 5:26:14 pm" but on the hosted Heroku app I get "August 15th 2018, 10:26:14 pm." I am expecting "August 15th 2018, 5:26:14 pm" because I'm opening the Heroku app in the same timezone, but it looks like it's giving me the server timezone.

What should I do to make sure the date/time shows up in the client's local timezone?
0
Identify and Prevent Potential Cyber-threats
Identify and Prevent Potential Cyber-threats

Become the white hat who helps safeguard our interconnected world. Transform your career future by earning your MS in Cybersecurity. WGU’s MSCSIA degree program was designed in collaboration with national intelligence organizations and IT industry leaders.

{
 "_id" : "Sh",

"Name" : "HR",
"Form" : [
    {
        "Name" : "HR",
        "Permission" : {},
        "Fields" : [
            {
                "OutputFormat" : "Text",
                "Validation" : [],
                "Name" : "PASS",
                "Permission" : {
                    "Hidden" : [
                        "ac"
                    ]
                },
                "IsFormulaArg" : false,
                "MaxCharacters" : 100.0,
                "Label" : "PASS",
                "Widget" : "Dropdown",
                "DefaultPermission" : [],
                "Dropdown" : "me",
                "Score" : 1,
                "PermissionType" : "Hidden",
                "Id" : "me"
            },


            {
                "OutputFormat" : "dd/MM/yyyy",
                "NodeList" : {
                    "Score" : 2,
                    "Type" : "CellReference",
                    "Id" : "jdk2",
                    "Value" : null,
                    "CellMetadata" : {
                        "72uw" : "CreatedAt"
                    }
                },
                "Name" : "Date_Prepared",
                "Permission" : {},
                "IsFormulaArg" : false,
                "Required" : true,
                "Widget" : "Date",
                "Label" : "Date Prepared",
                "Score" : 2,
                "FormulaStr" : "CreatedAt",
                **"Formula" : "True",**
      …
0
I am trying to install MongoDB on my hosted Linux box and getting this error.

I cannot seem to get it corrected after trying many different forum solutions.

Anyone have any thoughts?

My hosted system specs:
Operating system Debian Linux 8
Kernel and CPU Linux 3.16.0-5-amd64 on x86_64

 The following packages have unmet dependencies:
 mongodb-org : Depends: mongodb-org-server but it is not going to be installed
               Depends: mongodb-org-mongos but it is not going to be installed
               Depends: mongodb-org-tools but it is not going to be installed
 unifi : Depends: mongodb-server (>= 2.4.10) but it is not going to be installed or
                  mongodb-10gen (>= 2.4.14) but it is not installable or
                  mongodb-org-server (>= 2.6.0) but it is not going to be installed
         Depends: mongodb-server (< 1:3.6.0) but it is not going to be installed or
                  mongodb-10gen (< 3.6.0) but it is not installable or
                  mongodb-org-server (< 3.6.0) but it is not going to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

Open in new window


T.I.A.!
0
So i have a user schema like this:

var user_schema = new Schema({
   username:{type:String,required: true, unique : true, trim: true},
   college:{type:String,required: true},
   password:{type:String,required: true, trim: true},
   email:{type:String,required: true, unique : true, trim: true},
   phone:{type:Number,required: true, unique : true, trim: true},
   dp:{type:String},
   tag:{type:String},
   description:{type:String},
   friends:[{type:String}],
   pending:[{type:String}],
   skills:{type:String},
   bucket:[{type:String}]
  });

Open in new window

and my objective is, to search the all the documents in the collection to get people based on the following conditions:

1. They should not be in the users' "friends" array.
2. They should not be in the users' "pending" array.
3. They should have the same "tag" (a string value) as the user.

So, basically I have to compare the users' fields ("friends","pending" and "tags"), with fields of all documents in the whole collection.

How do I do it, using mongoose (nodejs mongodb library)
0
I have to initialize an array to [](empty array) and then push user chose "tags" into it. This is my schema:

 var user_schema = new Schema({
   username:{type:String,required: true, unique : true, trim: true},
   college:{type:String,required: true},
   password:{type:String,required: true, trim: true},
   email:{type:String,required: true, unique : true, trim: true},
   phone:{type:Number,required: true, unique : true, trim: true},
   dp:{type:String},
   tags:[{type:String}],
   description:{type:String},
   skills:{type:String},
   bucket:[{type:String}]
 }); 

Open in new window

` and i have to initialize "tags" to [] and push user string values (user entered/chosen) every time the request is made to the API call.

I am using this line of code:

 stu_user.findOneAndUpdate(
   { _id: req.decoded.id },
   { $set:{tags:[]},$push: { tags: 'some chosen string'  } },
  function (error, success) {
         if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });

Open in new window

But it's not working.
0
How to import collections from mongodb from cli?
0
Hey, This is just a decision-making problem. I am seeking for a well thought out answer.
I have to develop an android XMPP chat application, (the application also has a NodeJS server API, connecting to MongoDB and AWS S3 for picture uploads)

which will be better:

1. Having a "openfire" server on aws and connecting it to the android application and implementing an XMPP client on the android device using "smack" library.

2. Implementing a "xmpp-client" on NodeJS server side and scrape the results from this API to the Android device.
0
How do MongoDB and Active Directory go together?

I have a small bit of exposure to MongoDB and  Active Directory as well. But is there so synergy of using them together?

Curious..

Thanks
0
hi,

how DB2 work with MongoDB ?
0
In MongoDb collection a DateTime field is stored in MST dateTime format for over 1 millions of record for a older record and now new records in utc dateTime format,
  Is there any cost effective query to update the date property in collections for those old recordsin MST dateTime
  (update the registered date format from MST to UTC format i.e. update time + 7:00 hr of each of these record)? We have MongoDb 3.3 version.
0
Powerful Yet Easy-to-Use Network Monitoring
Powerful Yet Easy-to-Use Network Monitoring

Identify excessive bandwidth utilization or unexpected application traffic with SolarWinds Bandwidth Analyzer Pack.

I'm having difficulty putting a complex(to me) aggregation query together for my data. Basically, here's the run down so everyone understands my conundrum.

I have two collections in this equation. "training_documents" and "users". Each user object has a key identified by name "trainings" which is an array of objects. Each object within this trainings array, contains 4 key/value pairs. An example of each object is below.

    {
    	"document": ObjectId('5a0350ad7df0977d94cffab6'),
    	"trainee": ObjectId('59e51a4b7df0977d94cff95d'),
    	"trainer": ObjectId('595fcc2e04cf707693257890'),
    	"completion_time": "2018-04-23T21:28:22.747Z"
    }

Open in new window


The users trainings array will contain many objects following the aforementioned format.

An example user data structure is below for reference.

   
 [
    	{
    		"_id": "5ad782283c55b056bcc39e3z",
    		"site": {
    			"site_id": "site1",
    			"site_name": "Site One"
    		},
    		"user_name": "jsmith",
    		"first_name": "John",
    		"middle_name": "A",
    		"last_name": "Smith",
    		"full_name": "John Smith",
    		"title": "Duh Boss...",
    		"email": "testuser@example.com",
    		"last_login": "2018-04-27T14:27:27.014Z",
    		"type": "full-time",
    		"active": true,
    		"__v": 0,
    		"badge_id": "000001780343232123",
    		"trainings": [
    			{
    				"document": ObjectId('5ae33622a766885a121b7362'),
    				"trainee": 

Open in new window

0
hi,

what is the solution to integrate Oracle with Mongo DB? data flow between them ?
0
hi,

anyone know how to intergrate MariaDB and Mongo DB so that they work together well ?

how about MariaDB and hadoop?
0
hi,

anyone know how to intergrate MS SQL and Mongo DB so that they work together well ?

how about MS SQL and hadoop?
0
nodeJs and MongoDB
I Would like to  Create a dynamic navbar with mean stack a navbar that the admin can modify it navbar has
Main Categoy
Sub Categories title
sub category
example image https://prnt.sc/j3nxz7
0
Mongo vs. Postgres DB.  Can you anyone pointed pros and cons?  And from the personal experience advice?
0
Mongo 2.6.12

Not a mongo admin just trying to figure out an issue no one else wants to take on.

Mongo is flushing logs after 24 hours, where is that configuration set or better yet what command can I run against a collection to see the details of log retention?
0
Hi There,

I have a mongodb aggregate query in PHP that is throwing an error and I can't see what I've missed in the syntax.

Versions are
mongodb =  3.6
PHP  = 7.1
mongo PHP driver = 1.3.1-1


 The query in mongo shell works and looks like this:

db.products.aggregate(
	[
		{
			$match: {
			    download_Date : {'$gte' : 20180205 }
			}},
		{
			$sort: {
			download_Date: 1 }
		},
		{
			$group: {
			 _id: "$cw_product_id", batch: { $last : "$download_Date" }
	        }},
	]

Open in new window


My code in PHP fails and  looks like

$command = new MongoDB\Driver\Command([
    'aggregate' => 'products',
    'pipeline' => [    
        ['$match' =>  [ 'download_Date' => ['$gte' => $batch ]]],
        ['$sort'  => [  
            'download_Date' => 1
        ]],
    ['$group' => [ 
        '_id' => [ '$cw_product_id', 'batch' => ['$last' => '$download_Date'] ],
        ]],   
    ],
        'allowDiskUse' => true, 
        'cursor' => new stdClass, 
    ]);

Open in new window


The error I receive when running the php script is

           
PHP Fatal error:  Uncaught MongoDB\Driver\Exception\RuntimeException: Unrecognized expression '$last'

Open in new window

I've pulled it apart and put it back together so many times, a fresh pair of eyes is needed to spot the obvious.  

Thanks in advance,

Rick
0
Hi,

I have a text file which has multiple json rows in it.

What I need to do is the following:-

1. Read thru the file
2. Select only certain elements not all, remap to a new name for example AuthenticationId could be AuthId
3. Ingest in to MongoDB as JSON

How can this be achieved in Python?

{"AuthenticationId":"997","CommandLine":"C:\\Windows\\system32\\wbem\\wmiprvse.exe -secured -Embedding","ConfigBuild":"1007.3.0005907.1","ConfigStateHash":"3163607488","EffectiveTransmissionClass":"3","Entitlements":"15","ImageFileName":"\\Device\\HarddiskVolume3\\Windows\\System32\\wbem\\WmiPrvSE.exe","ImageSubsystem":"2","IntegrityLevel":"16384","MD5HashData":"1df2fc82b861bc9612657d1661e9ae33","ParentAuthenticationId":"997","ParentProcessId":"1627804482161","ProcessCreateFlags":"16","ProcessEndTime":"","ProcessParameterFlags":"24577","ProcessStartTime":"1512962460","ProcessSxsFlags":"64","RawProcessId":"9276","SHA1HashData":"1aa3fda50123dd14a055b4d6601beedead69fe11","SHA256HashData":"835f2a94e47830b06654e484bf7a1cc0b9882f579716dca198e32d22218a07e5","SourceProcessId":"1627804482161","SourceThreadId":"39913451443946","TargetProcessId":"1756187997441","TokenType":"2","UserSid":"S-1-5-19","aid":"2bc82f8878df4b9f7712273e755a93be","aip":"105.255.135.108","cid":"99cdff8f89af458d858c3d6b3e312e11","event_platform":"Win","event_simpleName":"ProcessRollup2","id":"4ff73eae-de22-11e7-a0dd-06e913674db2","name":"ProcessRollup2V6","timestamp":"1512962460994"}

Open in new window



Open in new window

0
The Lifecycle Approach to Managing Security Policy
The Lifecycle Approach to Managing Security Policy

Managing application connectivity and security policies can be achieved more effectively when following a framework that automates repeatable processes and ensures that the right activities are performed in the right order.

Hello. I am working on a node application.  I'm trying to use Passport for the log in.   I found an example online of what I want to do.  However I cannot get it to work.  I am running into an issue with my routes.  I get a compiler error that I have not seen before.  I tried to attached the project to this question, but it won't accept zip files so I will just attach my index.js and AuthController.js.  This is the error I get on index.js when it tries to do my first route.
 
var auth = require("../controllers/AuthController.js");

// restrict index for logged in user only
router.get('/', auth.home);

Open in new window

I get this error:  
index.js:349
throw new mongoose.Error.OverwriteModelError(name);
OverwriteModelError: Cannot overwrite `User` model once compiled.
at MongooseError.OverwriteModelError (C:\Users\ernest\Documents\coding bootcamp\code\Passport MongoDB\node-passport-auth\node_modules\mongoose\lib\error\overwriteModel.js:18:11)
    at Mongoose.model (C:\Users\ernest\Documents\coding bootcamp\code\Passport MongoDB\node-passport-auth\node_modules\mongoose\lib\index.js:349:13)
    at Object.<anonymous> (C:\Users\ernest\Documents\coding bootcamp\code\Passport MongoDB\node-passport-auth\models\user.js:12:27)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require …
0
MongoDB v2.6.12 keeps losing my user credentials on a database. I'm running Iquidus Explorer and thus need to be running v2.6.x of MongoDB for it to work. Most of the time it works fine, but every now and again my script disconnects and gets an error that the user credentials are no longer correct.

To fix this I have to run mongo and type use database1 and then db.createUser( { user: "username", pwd: "blahblah", roles: [ "readWrite" ] } )

This is far from ideal. Can anyone shed any light on what's going on and how to prevent the credentials from getting screwed up?

I'm running MongoDB on CentOS 7 64-bit.
0
I've been thinking to migrate my erp(java currently) from rdbms(firebird currently) to nosql (mongoDB likely) and i trying to antecipate some issues. I'm trying to make a "failproof" inventory control which never let a qty's item be smaller than 0. Offcourse i still get "ACID bias" which i need to left in order to complete this task. The goal is update inventory qty of all order's items when approve the order. For that, 2 problems can occur which currently are resolved with a trigger.

1.problem: order gets 2 items (ball = qty 2 and chair = qty 1) and there is no enough qty in inventory (ball = qty 1 and chair = qty 0) to complete the order. Once i trigger the command do complete the order, a loop is executed to decrease qty in inventory and fails on the second item cause there is no enough qty. Consequently rollback operation is trigged and everybody go home happy.

2.problem: in one word, concurrency. suppose there is no trigger controling this operation but only "selects and if". User 1 query inventory qtys, see enough qty (ball = 2, chair = 1) e system allow complete the order. While the transaction is running user 2 query same invetory qtys but because first transaction is not complete yet second query see "old" qty (ball = 2, chair = 1) e system also lets complete order. Consequently, 1 qty of chair is descreased twice, but shold be descreased only once and fail on the second. Result: i got negative qty.

I saw some workarrounds with inventory reservation but i …
0
Created a duplicate username entry in mongoose database and resulted in duplicated error. Now everytime I start server, I get this error:

(node:14839) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "{ type: 'Buffer',
  data: [ 89, 243, 30, 231, 66, 69, 45, 56, 123, 65, 153, 72 ] }" at path "_id" for model "users"
(node:14839) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
0
I am trying to update a dict with values searched from mongoDB whose parameters are taken from another dict. What I have till now is:

    lst = {'a':1}
    b={'Name':'name_1', 'Address':'Address_1'}
    lst.update(k:coll.find({"_id":id}{v:1})) for k,v in b.items()

What is the right way to do this procedure?
0
Hi, I have the following document and I want to delete all keys that are empty:

so it should delete the key year from first instance and build on second instance since is empty. I want the query to update all documents and clear that array of options of empty values.

{
    _id: 'sldkfjsldkf',
    name: "Red car",
    options: [
       {
          color: "red",
          year: "",
          build: "2000"
       },
       {
          color: "yellow",
          year: "1988",
          build: ""
       },
  ]

}
0

MongoDB

133

Solutions

246

Contributors

MongoDB (from humongous) is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. MongoDB is developed by MongoDB Inc. and is free and open-source, published under a combination of the GNU Affero General Public License and the Apache License.

Top Experts In
MongoDB
<
Monthly
>