MongoDB Visual Studio Code extension: how to find by ObjectId - mongodb

I'm using the following extension:
https://code.visualstudio.com/docs/azure/mongodb
To perform queries and light data transformation against a Mongo database. I'm having trouble working out how to issue a find request which matches an ObjectId.
I tried:
db.Epochs.find({
'ModelId': '624616797870316ac1432d52'
}).sort({'End': -1})
This results in an empty result set (this ID definitely exists because I copied that value from Compass.
I tried:
db.Epochs.find({
'ModelId': ObjectId'624616797870316ac1432d52')
}).sort({'End': -1})
Which results in the following error:
Unexpected token, expected "," (15:23) 13 | 14 | db.Epochs.find({ > 15 | 'ModelId': ObjectId('624616797870316ac1432d52') | ^ 16 | }).sort({'End': -1}) 17 | 18 | //'EndLogs._impl': { '$exists': true}
I tried adding the NodeJS driver setup calls like:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
Which errors with:
Cannot find module 'mongodb' Require stack: - c:\Users\Ian\.vscode\extensions\mongodb.mongodb-vscode-0.9.2\dist\languageServerWorker.js
Finally I tried:
db.Epochs.find({
'ModelId': { '$oid': '624616797870316ac1432d52' }
}).sort({'End': -1})
Which errors with:
unknown operator: $oid

Related

TypeError: Cannot destructure property 'createNode' of 'boundActionCreators' as it is undefined

Can anyone help with following error ?
ERROR #11321 PLUGIN
"gatsby-source-firestore" threw an error while running the sourceNodes lifecycle:
Cannot destructure property 'createNode' of 'boundActionCreators' as it is undefined.
24 | const db = firebase.firestore();
25 |
26 | const { createNode, createNodeField } = boundActionCreators;
^
27 |
28 | const promises = types.map(
29 | async ({ collection, type, populate, map = node => node }) => {
File: node_modules\gatsby-source-firestore\gatsby-node.js:26:11
TypeError: Cannot destructure property 'createNode' of 'boundActionCreators' as it is undefined.
Replacing boundActionCreators by actions in gatsby-node.js present in node modules/gatsby-source-firestore
worked

find or aggregate by date

I have a date in my document. How do I query for all documents that are no more than 7 days old. I cannot assume that the time on the requestor machine and the database are in sync.
You can get the server datetime using "serverStatus" command:
In mongo shell:
server_time = db.adminCommand("serverStatus")['localTime'].getTime();
db.mycollection.find( { "change_date": { $gt: new Date((server_time) - 7 * 24 * 60 * 60 * 1000) }} )
In Java:
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("dbname");
Document serverStatus = database.runCommand(new Document("serverStatus", 1));
Instant server_time = (Instant) serverStatus.get("localTime");

Why is there an Authentication error whilst using pymongo authentication?

When I am trying to authenticate mongodb by using pymongo, it shows the below error,
command SON([('saslStart', 1), ('mechanism', 'SCRAM-SHA-1'),
('autoAuthorize', 1), ('payload',
Binary('n,,n=user,r=Mzk1NDU4ODUwNzU4', 0))]) on namespace
the_database.$cmd failed: Authentication failed.
My authentication code
client.fw_mongo.authenticate('user', 'password' )
fw_mongo is my mongodb name
What is wrong with this code?
Your code is correct, but your password is not the same as you configured MongoDB with.
try:
from pymongo import MongoClient
Client = MongoClient("mongodb://" + username + ":" + password + "server_details")
def collection_object():
db = Client.db_name
collection = db.collection_name
return collection

Error in connecting MongoDB on Amazon EC2 using pymongo

I'm trying to use MongoDB on Amazon EC2 using Python3.4.3.
I followed this answer: modified security groups setting and edited "/etc/mongod.conf" (comment out bind_id). However, when I run following code, I got this error:
ServerSelectionTimeoutError: SSL handshake failed: [Errno 54] Connection reset by peer
What else should I do?
The code I run is:
import pymongo
import ssl
client = pymongo.MongoClient('ec2-**-**-*-**.us-west-2.compute.amazonaws.com', 27017,
ssl=True, ssl_keyfile='/Users/S/FILENAME.pem')
db = client["test"]
db.artist
collection = db.artist
import gzip
import json
from io import StringIO
with gzip.open('artist.json.gz', "rt") as a_file:
count=0
bulk = []
for line in a_file:
jdata = json.load(StringIO(line))
bulk.append(jdata)
count += 1
if 1000 < count:
print ('bulk insert!')
collection.insert_many(bulk)
bulk = []
count = 0
if len(bulk) > 0:
collection.insert_many(bulk)

Not able to get all records in mongoDB using pymongo

I am having a program which uses pymongo to get the records in the mongoDB.
But, when I find records with a query I am getting blank cursor with no records.
Below is a code :
MongoDBConnection.py
import bottle
import pymongo
from pymongo import MongoClient
class MongoDBConnection():
def __init__(self):
pass
def getConnection(self,host):
try:
retConnection = MongoClient(host)
except Exception as e:
print 'Exception occurred while creating connection with mongoDB, value: \n '
print e
return retConnection
def showAllRecords(self,host,db,collection):
#pdb.set_trace()
hconn = self.getConnection(host)
hdb = self.getDBDetails(hconn,db)
hcoll = self.getCollectionDetails(hdb,collection)
#get all the details about the collection
query = {"name" : "SP"}
try:
cursor = hcoll.find(query)
except Exception as e:
print "Unexpected error:", type(e), e
return cursor
def getDBDetails(self,connection,db):
# create a database connection
try :
retDb = connection.db
except Exception as e:
print 'Exception occurred while connecting to database %s, value: \n ' % db
print e
return retDb
def getCollectionDetails(self,db,collection):
#create a handle for collection
try :
retCollection = db.collection
except Exception as e:
print 'Exception occurred while getting details for collection: %s, value: \n ' % collection
print e
return retCollection
A program which accesses this class:
runmongo.py
from MongoDBConnection import MongoDBConnection
a = MongoDBConnection()
test = a.showAllRecords("mongodb://localhost","test","documents")
print test
for i in test:
print i
The Output I am getting is a cursor object with no records in it.
[root#localhost tmp]# python runmongo.py
<pymongo.cursor.Cursor object at 0x288cd90>
[root#localhost tmp]#
Manually tried the same and I am getting proper output
> use test
switched to db test
> db.documents.find({'name':'SP'})
{ "_id" : "doc2", "name" : "SP" }
>
Can someone let me know, why am I not able to get the desired records from DB.
The problem is in accessing database and collection line itself.
When you try to access database and collection using attribute style like
retDb = connection.db
it assumes that 'db' is name of database instead of 'test' in your example.
Using dictionary style access will solve your problem something like this
retDb = connection[db]
Code goes like this :
import pymongo
from pymongo import MongoClient
class MongoDBConnection():
def __init__(self):
pass
def getConnection(self,host):
try:
retConnection = MongoClient(host)
except Exception as e:
print 'Exception occurred while creating connection with mongoDB, value: \n '
print e
return retConnection
def showAllRecords(self,host,db,collection):
#pdb.set_trace()
hconn = self.getConnection(host)
hdb = self.getDBDetails(hconn,'test')
hcoll = self.getCollectionDetails(hdb,'documents')
#get all the details about the collection
query = {"name" : "SP"}
try:
cursor = hcoll.find(query)
except Exception as e:
print "Unexpected error:", type(e), e
return cursor
def getDBDetails(self,connection,db):
# create a database connection
try :
retDb = connection[db] # NOTE : dictionary style access
except Exception as e:
print 'Exception occurred while connecting to database %s, value: \n ' % db
print e
return retDb
def getCollectionDetails(self,db,collection):
#create a handle for collection
try :
retCollection = db[collection] # NOTE : dictionary style access
except Exception as e:
print 'Exception occurred while getting details for collection: %s, value: \n ' % collection
print e
return retCollection