Use variables on MongoDB query

My basic MongoDB query

test.find({$or : [{"timeIn":"2018-1-31 11:57"},{"timeIn":"2018-1-31 11:58"},{"timeIn":"2018-1-31 11:59"},{"timeIn":"2018-1-31 12:00"},{"timeIn":"2018-1-31 12:01"},{"timeIn":"2018-1-31 12:02"},]})

I want use variables for replace expression and I tried

    //console.log(expression);
    test.find({"$or" : [expression]  }, {"email": 1, "_id": 0}).toArray(function (err,data){
      if (err) throw err;
      console.log(data);
});

But got a error

MongoError: $or/$and/$nor entries need to be full objects

With variables expression are {"timeIn":"2018-1-31 11:57"},{"timeIn":"2018-1-31 11:58"},{"timeIn":"2018-1-31 11:59"},{"timeIn":"2018-1-31 12:00"},{"timeIn":"2018-1-31 12:01"},{"timeIn":"2018-1-31 12:02"},

How I can use variables on MongoDB query?

How to structure a Node MongoDB project?

In my Node.js project with mongodb.js (note, not mongoose) I have the following structure:

  • index.js
    • sets up db connection (db.js)
    • sets up express server (api.js)
  • api.js
    • starts the server
    • defines routes and calls db (db.js)
  • database.js
    • starts db connection, db is defined as a global in the file
    • each db function uses the global db variable

Roughly like this:

// database.js
let db;

module.exports = {
    connect() {
       db = set value here;
    },
    findUser() {
      db.find(query);
    }
};

Now I’d like to restructure each db function to it’s own folder like database/user.js, but I’m not sure how to handle the global db var with separate files?

// database/users.js
module.exports = {
    findUser() {
        db.find(query); <-- how to pass the db connection
    }
};

I’d like to avoid having to pass the db as parameter to all functions. What’s the common way to structure this?

increment a value in a sub-document in array if exist, otherwise push with upsert

I’m building a shopping cart system using react, node.js and mongodb.

I’m stuck with a problem:
Every time a customer visits a product details page, the client doesn’t know if that product exists in that customer’s cart. So if that customer clicks the add to cart button, the server would assume that the customer is incrementing the quantity of that product in the shopping cart and setting the buyNow field to true. But if that product doesn’t exist yet, it would push the product to items field in the cart document.

here is my cart collection

{
  _id: 'f64f2940-fae4-11e7-8c5f-ef356f279131', // uses user session or cookie
  lastModified: ISODate("2012-03-09T20:55:36Z"),
  status: 'active',
  items: [
    { productID: '5a819b322172431f10cee9da', qty: 3, buyNow: true },
    { productID: '5a79e0d3851ea81978406a67', qty: 1, buyNow: false }
  ]
}

How would you approach this problem ? is it possible with upsert operation ?
Thanks in advance..

how to use mongodb filter using regex and or c# driver

Can some one please help me on mongodb C# driver for regex with $or condition.

var collection = DB.GetCollection<BsonDocument>(SelectedCategory.Name);<br /> var builder = Builders<BsonDocument>.Filter;<br /> var filter1=builder.Regex("attributes." + attribute.Name, new<br /> BsonRegularExpression(".*" + attribute.AttributeValue + ".*"));

Find data without repetitions multiple documents in MongoDB

Good morning, I am learning MongoDB but when trying to make a query I do not achieve the desired results.

The structure of the documents used is as follows:

use empresa

db.departamento_dos.insert (
{
 "Codigo": 2,
 "Nombre": "Contabilidad",
 "Presupuesto": 10000,
 "Empleados": 
 {
  "Empleado": { "DNI": "10340", "Nombre": "Andres", "Apellido": "Lopez"},
  "Empleado": { "DNI": "10341", "Nombre": "Paula", "Apellido": "Tovar"},
  "Empleado": { "DNI": "10342", "Nombre": "Andres", "Apellido": "Perez"},
  "Empleado": { "DNI": "10343", "Nombre": "Camila", "Apellido": "Perez"},
  "Empleado": { "DNI": "10344", "Nombre": "Cristian", "Apellido": "Forero"}
 }
}
)

and

db.departamento_tres.insert (
{
 "Codigo": 77,
 "Nombre": "Marketing",
 "Presupuesto": 30000,
 "Empleados": 
 {
  "Empleado uno": { "DNI": "10350", "Nombre": "Maria", "Apellido": "Perez"},
  "Empleado dos": { "DNI": "10351", "Nombre": "Angie", "Apellido": "Gómez"},
  "Empleado tres": { "DNI": "10352", "Nombre": "Andrea", "Apellido": "Lopez"},
  "Empleado cuatro": { "DNI": "10353", "Nombre": "Cristina", "Apellido": "Riaño"},
  "Empleado cinco": { "DNI": "10354", "Nombre": "Annie", "Apellido": "Castellanos"}
 }
}
)

My question is: how can I make a query by “Apellido” by eliminating repeated “Apellidos”?

I tried to use the different operator with a regular expression to auto-complete the query, but not work.

db.departamento_uno.distinct( "Empleados.Empleado", { /.*".Apellido"} )

and it always shows me an empty vector.

The idea is to be able to consult the two documents simultaneously. For example, the result I’m looking for would be:

[ "Lopez", "Tovar", "Perez", "Forero", "Gómez", "Riaño", "Castellanos"]

since the idea is to show each surname only once no matter how many times it appears

Any idea how you can make this query?

Thanks for the help.

Linq Join Error: The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to ‘Join’

This is the code i’ve tried to join two collections its not working please help

var query = from p in collection.AsQueryable()  
            join o in collection1 
               on p.tag_description equals o.key into joined 
            from sub_o in joined.DefaultIfEmpty()
             select new { p.tag_id, sub_o.record_hour };

MongoDB: upsert sub-document

I have documents that looks something like that, with a unique index on bars.name:

{ name: 'foo', bars: [ { name: 'qux', somefield: 1 } ] }

. I want to either update the sub-document where { name: 'foo', 'bars.name': 'qux' } and $set: { 'bars.$.somefield': 2 }, or create a new sub-document with { name: 'qux', somefield: 2 } under { name: 'foo' }.

Is it possible to do this using a single query with upsert, or will I have to issue two separate ones?

Related: ‘upsert’ in an embedded document (suggests to change the schema to have the sub-document identifier as the key, but this is from two years ago and I’m wondering if there are better solutions now.)

Local MongoDB server not starting

I am starting to learn NodeJS and Express framework. I was following a tutorial where I had a basic application

const express = require('express');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');

const app = express();

mongoose.Promise = global.Promise
// mongoose
mongoose.connect('mongodb://localhost/vidjot-dev')
.then(() => console.log("Mongo DB started"))
.catch(err => console.error(err));

// handlebars middleware
app.engine('handlebars', exphbs({
  defaultLayout: 'main'
}));
app.set('view engine','handlebars')


// index route
app.get('/', (req, res) =>{
  const title = "Welcome"
  res.render('index',{
    title : title
  });
});

app.get('/about', (req,res) =>{
  res.render('about');
});

const port = 5000;

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

I tried to start the node js server from the console using the command

nodemon app

Where app is the name of the JS file app.js

When I tried to start the server, I got this error

{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (/Users/sriramr/Desktop/node/vidjot/node_modules/mongodb-core/lib/topologies/server.js:503:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (/Users/sriramr/Desktop/node/vidjot/node_modules/mongodb-core/lib/connection/pool.js:326:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (/Users/sriramr/Desktop/node/vidjot/node_modules/mongodb-core/lib/connection/connection.js:245:50)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'MongoNetworkError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }

I tried setting the DB path again but it wasn’t of any use. I tried to start mongod from the terminal but got the same error again. How do I fix this?

EDIT:
I have the directories data/db created and I just ran

mongod --dbpath <DIRECTORY>

and got this error

2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] MongoDB starting : pid=76227 port=27017 dbpath=/Users/sriramr/mongodb/data/db 64-bit host=MACBOOKs-MacBook-Air.local
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] db version v3.6.2
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] git version: 489d177dbd0f0420a8ca04d39fd78d0a2c539420
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 0.9.8zh 14 Jan 2016
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] allocator: system
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] modules: none
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] build environment:
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten]     distarch: x86_64
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten]     target_arch: x86_64
2018-02-16T17:42:02.657+0530 I CONTROL  [initandlisten] options: { storage: { dbPath: "/Users/sriramr/mongodb/data/db" } }
2018-02-16T17:42:02.659+0530 I -        [initandlisten] Detected data files in /Users/sriramr/mongodb/data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2018-02-16T17:42:02.660+0530 I STORAGE  [initandlisten] exception in initAndListen: InvalidOptions: Requested option conflicts with current storage engine option for directoryPerDB; you requested false but the current server storage is already set to true and cannot be changed, terminating
2018-02-16T17:42:02.661+0530 I NETWORK  [initandlisten] shutdown: going to close listening sockets...
2018-02-16T17:42:02.661+0530 I NETWORK  [initandlisten] removing socket file: /tmp/mongodb-27017.sock
2018-02-16T17:42:02.661+0530 I CONTROL  [initandlisten] now exiting
2018-02-16T17:42:02.661+0530 I CONTROL  [initandlisten] shutting down with code:100

Can I get top 10 group list from MongoDb which is order by members count

I have 2 collections one is for group details and other is for group_members details,
group_members have group’s _id stored (as FK)

Like
group : -> _id,name,type,date

group_members -> _id,group_id,members_id,role,status

so how can I get the groups that have most count of memebrs in that with order by group_membrs’s count (top 10 groups with more members)