I know how to list all collections in a particular database, but how do I list all available databases in MongoDB shell?
Listing all the databases in mongoDB console is using the command show dbs.
For more information on mongo shell commands, refer the Mongo Shell Quick Reference.
For database list:
show databases
show dbs
For table/collection list:
show collections
show tables
db.getCollectionNames()
For MongoDB shell version 3.0.5 insert the following command in the shell:
db.adminCommand('listDatabases')
or alternatively:
db.getMongo().getDBNames()
From the command line issue
mongo --quiet --eval "printjson(db.adminCommand('listDatabases'))"
which gives output
{
"databases" : [
{
"name" : "admin",
"sizeOnDisk" : 978944,
"empty" : false
},
{
"name" : "local",
"sizeOnDisk" : 77824,
"empty" : false
},
{
"name" : "meteor",
"sizeOnDisk" : 778240,
"empty" : false
}
],
"totalSize" : 1835008,
"ok" : 1
}
to obtain a vertical list of all databases for downstream processing do this
mongo --quiet --eval "printjson(db.adminCommand('listDatabases'))" | jq '.databases[].name' | tr -d '"'
which gives below output listing all databases
admin
local
meteor
To list mongodb database on shell
show databases //Print a list of all available databases.
show dbs // Print a list of all databases on the server.
Few more basic commands
use <db> // Switch current database to <db>. The mongo shell variable db is set to the current database.
show collections //Print a list of all collections for current database.
show users //Print a list of users for current database.
show roles //Print a list of all roles, both user-defined and built-in, for the current database.
Couple of commands are there to list all dbs in MongoDB shell.
first , launch Mongodb shell using 'mongo' command.
mongo
Then use any of the below commands to list all the DBs.
show dbs
show databases
db.adminCommand( { listDatabases: 1 , nameOnly : true} )
For more details please check here
Thank you.
I have found one solution, where admin()/others didn't worked.
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
async function test() {
var res = await exec('mongo --eval "db.adminCommand( { listDatabases: 1 }
)" --quiet')
return { res }
}
test()
.then(resp => {
console.log('All dbs', JSON.parse(resp.res.stdout).databases)
})
test()
According to MongoDB official document, for MongoDB 4+, you can list database name only by running db.adminCommand( { listDatabases: 1, , nameOnly: true } ) against the admin database.
If you are using MongoDB Cloud, you need to connect to your MongoDB deployment first. In that case, you can run this command mongosh "mongodb+srv://cluster0.<your-connection-string>.mongodb.net" --apiVersion 1 --username <your-user-name> in your terminal.
Atlas atlas-xxxxxx-shard-0 [primary] test> db.adminCommand({listDatabases:1 , nameOnly: true})
{
databases: [
{ name: 'sample_airbnb' },
{ name: 'sample_analytics' },
{ name: 'sample_geospatial' },
{ name: 'sample_guides' },
{ name: 'sample_mflix' },
{ name: 'sample_restaurants' },
{ name: 'sample_supplies' },
{ name: 'sample_training' },
{ name: 'sample_weatherdata' },
{ name: 'admin' },
{ name: 'local' }
],
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: xxxxxxxxxx, i: 1 }),
signature: {
hash: Binary(Buffer.from("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "hex"), 0),
keyId: Long("xxxxxxxxxxxxx")
}
},
operationTime: Timestamp({ t: xxxxxxxxxx, i: 1 })
}
Related
i have this issue with Sequelize:
I'm trying to have a 3 parameter research and if one of those parameter is empty it should not consider that parameter.
const users = await User.findAll({
where: {
category: { [Op.like]: `%${req.query.category}%` },
location: { [Op.like]: `%${req.query.location}%` },
[Op.or]: [
{ job: { [Op.like]: `%${req.query.job}%` } },
{ bio: { [Op.like]: `%${req.query.job}%` } },
{ skills: { [Op.like]: `%${req.query.job}%` } },
],
},
attributes: { exclude: ['password', 'createdAt', 'updatedAt'] },
})
I've found out that the [Op.like] is not working anywhere.
It only works if a parameter is empty (blocks that parameter from filtering the users and that's something i like).
When i do a research with the example payload {category:'Information Technology', job:'frontend web dev', location:'Sydn'} this is logged in the process log:
Executing (default): SELECT `id`, `email`, `firstName`, `lastName`, `image`, `location`, `phone`,
`website`, `availability`, `category`, `job`, `skills`, `bio` FROM `Users` AS `User`
WHERE (`User`.`job` LIKE '%frontend web dev%' OR `User`.`bio` LIKE '%frontend web dev%' OR
`User`.`skills` LIKE '%frontend web dev%') AND `User`.`category` LIKE '%Information Technology%'
AND `User`.`location` LIKE '%Sydn%';
but no user is found. (yes, in the database I have users with similar parameters)
In my opinion your code and your logged SQL are same. I don't see any errors. Maybe you should try to copy that SQL and paste it in MySQL Workbench (if you're using MySQL) then try to run it.
I think it should looks more like this:
category: { [Op.like]: '%`${req.query.category}%`' },
What I did here is add single quote mark '. Reference to the documentation
I have an MongoDB Stitch app, that users the Email/Password authentication. This creates users within the Stitch App that I can authenticate on the page. I also have an MongoDB Atlas Cluster for my database. In the cluster I have a DB with the name of the project, then a collection underneath that for 'Matches'. So when I insert the 'Matches' into the collection, I can send the authenticated user id from Stitch, so that I have a way to query all Matches for a particular User. But how can I add additional values to the 'User' collection in stitch? That user section is sort of prepackaged in Stitch with whatever authentication type you choose (email/password). But for my app I want to be able to store something like a 'MatchesWon' or 'GamePreference' field on the 'User' collection.
Should I create a collection for 'Users' the same way I did for 'Matches' in my Cluster and just insert the user id that is supplied from Stitch and handle the fields in that collection? Seems like I would be duplicating the User data, but I'm not sure I understand another way to do it. Still learning, I appreciate any feedback/advice.
There isn't currently a way to store your own data on the internal user objects. Instead, you can use authentication triggers to manage users. The following snippet is taken from these docs.
exports = function(authEvent){
// Only run if this event is for a newly created user.
if (authEvent.operationType !== "CREATE") { return }
// Get the internal `user` document
const { user } = authEvent;
const users = context.services.get("mongodb-atlas")
.db("myApplication")
.collection("users");
const isLinkedUser = user.identities.length > 1;
if (isLinkedUser) {
const { identities } = user;
return users.updateOne(
{ id: user.id },
{ $set: { identities } }
)
} else {
return users.insertOne({ _id: user.id, ...user })
.catch(console.error)
}
};
MongoDB innovates at a very fast pace - and while in 2019 there wasn't a way to do this elegantly, now there is. You can now enable custom user data on MongoDB realm! (https://docs.mongodb.com/realm/users/enable-custom-user-data/)
https://docs.mongodb.com/realm/sdk/node/advanced/access-custom-user-data
const user = context.user;
user.custom_data.primaryLanguage == "English";
--
{
id: '5f1f216e82df4a7979f9da93',
type: 'normal',
custom_data: {
_id: '5f20d083a37057d55edbdd57',
userID: '5f1f216e82df4a7979f9da93',
primaryLanguage: 'English',
},
data: { email: 'test#test.com' },
identities: [
{ id: '5f1f216e82df4a7979f9da90', provider_type: 'local-userpass' }
]
}
--
const customUserData = await user.refreshCustomData()
console.log(customUserData);
The Community Connector feature is very new, and I have searched, there isn't much information. We are building a Community Connector to enable Data Studio to pull API data from Google My Business Insights.
the getconfig() function is described here: https://developers.google.com/datastudio/connector/reference#getconfig
We can display our configuration options to the user, that was easy, but the API reference is unclear what the next step is: how to pass the user input to the next step. Pardon me if I am not using the proper terms here.
var config = {
configParams: [
{
"type": "SELECT_SINGLE",
"name": "SELECT_SINGLE",
"displayName": "Select a Location",
"helpText": "Pick One!",
"options": [
{
"label": locationName,
"value": name
},
{
"label": "altLocationName",
"value": "altName"
}
]
},
]
};
return config;
}
The preceding code displays properly to the user and the user can make a selection from the pull-down in Data Studio when making an initial data connection. But to repeat the question another way: how do we access the selection that the user chose?
The getData(), getSchema(), and getConfig() functions are all called with a parameter (which is called "request" in the documentation). The parameter is an object containing various info at each stage.
At the getConfig() stage, it includes a property called languageCode, in my case set to 'en-GB'.
The getSchema() stage is provided a property called configParams, which is essentially the result of all the settings in getConfig() after the user has set them.
Finally, getData() gets the most info, including whether this request is for extracting sample data for google to run heuristics on, and most importantly: again the configParams.
Here's what a sample request object might look like:
{ //------ Present in:
languageCode: en-GB, //////-Only getConfig()
configParams: { //////-getSchema() + getData()
SELECT_SINGLE: altName ////-+
}, //
scriptParams: { //////-Only getData()
sampleExtraction: true ////-|
lastRefresh: 'new Date()' ////-+
}, //
fields: [ //////-Only getData()
{ name: FooAwesomeness }, ////-|
{ name: BarMagicality }, ////-|
{ name: BazPizzazz } ////-+
] //
dimensionsFilters: [ //////-Only getData()
[{ // |
fieldName: "string", ////-|
values: ["string", ...], ////-|
type: DimensionsFilterType, ////-|
operator: Operator ////-+
}] //
] //
} //------
Do note
that the name field in your code, currently set to SELECT_SINGLE, would be better suited to be called location because that it how you'll access it later on.
In this way you would
access:
request.configParams.location
rather than
request.configParams.SELECT_SINGLE
:)
Also note
that the format for specifying a configuration screen has been updated. Your configuration would now be able to be done as follows:
function getConfig(request) {
var cc = DataStudioApp.createCommunityConnector();
var config = cc.getConfig();
config
.newSelectSingle()
.setId('location') // You can call this "location"
.setName('Select a Location')
.setHelpText('Pick One!')
.addOption(config.newOptionBuilder()
.setLabel('Location Name')
.setValue('value'))
.addOption(config.newOptionBuilder()
.setLabel('Alternate Location Name')
.setValue('altValue'))
config.setDateRangeRequired(true);
config.setIsSteppedConfig(false);
return config.build();
}
See: Connector API Reference
See: Build a Connector Guide
The user selections will be passed to getSchema() and getData() requests under configParams object.
Using your example, let's assume the user selects altLocationName in the configuration screen. In your getSchema() and getData() functions, request.configParams.SELECT_SINGLE should return altName.
I need to fetch list
I have Schema
export const Schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
activities: {
name: 'Activities',
type: new GraphQLList(activityType),
resolve: (root, args, { rootValue }) => {
return User.findById(rootValue.req.user.id)
.populate('activities')
.then((user) => user.activities);
},
},
When I do graphql request using curl and sends
query ActivitiesQuery {
activities {
name
}
}
it gives me
{
"data": {
"activities": [
{
"name": "Eat"
}
]
}
}
Can somebody give me example how can I fetch it using relay ? because all the examples give object and then list like Store: { teas: [...
activities is an example of a plural non-identifying field. It is plural in the sense that it returns a list of things, and non-identifying in the sense that the individual elements of that list are not identified by global IDs.
Relay does not support plural non-identifying fields at the root, but support is coming. Follow along at https://github.com/facebook/relay/issues/112
There's a dev database already set up for another project. I'm trying to create a sails.js server to connect to this database and act as a RESTful API. I'm also using SQL Workbench with the profile below to connect to the database and verify my query statements. On that tool, I'm able to send queries like select top 10 * from advisor and get the data I expect in response.
My connection configuration in sails.js seems to be alright, since I'm able to start the server. I've gotten simple static actions to work, like hi: function (req, res) { return res.send("Hi there!"); }. However, I can't figure out what to do to get a response from the database served by sails. My goal (at this point) is to have http://localhost:1337/advisor return JSON for the results of select top 10 * from advisor.
I initially tried using the freshly-generated model. Then, I tried adding attributes to the model file. Then, I tried adding my own code to the controller. In each case, the browser never received a response. At the end, I tested /advisor/list to run my own code and it doesn't look like the query() callback was ever executed. In case it's the first question, I have run npm install sails-sqlserver and I've double-checked that my host, db, username, & password are identical to what was used in Workbench.
connections.js
sqlserver: {
adapter: 'sails-sqlserver',
user: 'myusername',
password: 'mypassword',
host: 'mysubdomain.mydomain.net:1433',
database: 'frontofficedev'
}
models.js
module.exports.models = {
connection: 'sqlserver',
migrate: 'safe'
};
api\models\Advisor.js
module.exports = {
attributes: {
advcode: 'string',
advname: 'string',
'adv-default': 'boolean',
"user-id": 'string',
"pc-code": 'string',
"adv-tag": 'string',
"is-group": 'boolean',
"trade-grouping": 'string',
AdvisorId: 'int',
orgcode: 'string',
BranchId: 'int',
OrdPrnBranchId: 'int',
zdec1: 'float',
zdec2: 'float',
zchar1: 'string',
zchar2: 'string',
zchar3: 'string',
zchar4: 'string',
AdvStatus: 'string'
}
};
api\controllers
module.exports = {
hi: function (req, res) {
return res.send("Hi there!");
},
list: function (req, res) {
var myQuery = "select TOP 10 * from advisor";
sails.log.debug("Query :", myQuery);
console.log(Advisor);
Advisor.query(myQuery, function (err, advisors){
console.log(advisors);
console.log(err);
if(err || !advisors.rows.length){
return res.json({"status": 0, "error": err});
}
else{
return res.json(advisors);
}
});
}
};
Any ideas on what I'm doing wrong? Is JDBC causing problems? Thanks in advance.
Im assuming you've already run: npm install sails-sqlserver --save
You have to specify your connection and the table you will be using in the model, the variables in the model should match with your DB variables, like this:
api\models\Advisor.js
module.exports = {
schema: true,
connection: 'sqlserver',
tableName: 'yourTableName',
attributes: {
advcode:{
type: 'string',
primaryKey: true //if this is a primary key
},
advname:{
type: 'string'
},
'adv-default':{
type: 'boolean'
}
};
In your controller you can use the Sails ORM waterline like this:
api\controllers
module.exports = {
list: function (req, res) {
Advisor.query('SELECT * FROM advisor', function(err, results) {
if (err) {
res.send(400);
} else {
res.send(results);
}
});
}
};
Where Advisor is the model.
For more specific information about models and ORM waterline i recommend you read the sails docs: http://sailsjs.org/documentation/reference/waterline-orm/models
My colleague spotted the problem. The port that database lives on needs to be a separate attribute in sails' connection.js (instead of including it in the host string). No need for extra libraries, like node-jdbc.
config/connections.js
sqlserver: {
adapter: 'sails-sqlserver',
user: 'myusername',
password: 'mypassword',
host: 'mysubdomain.mydomain.net',
port: 1433,
database: 'frontofficedev'
}
After making that change, I was able to delete all my custom code from the controller and almost everything from the model (I still need to specify a primary key, since sails looks for id by default and the database was using AdvisorId.
api/models/Advisor.js
module.exports = {
attributes: {
AdvisorId: {primaryKey: true}
}
};