mongoose list collections of a specific database - mongodb

I use the following code to list the collections of the current database, but how to list the collections of another one?
mongoose.connection.db
.listCollections()
.toArray()
.then(coll => console.log({ coll }));

At one time you can see collections regarding only one Database. So if you need to list another database collections, you just need to change the corresponding DB name in the DB connection function. (Simply you can change the connection URL DB name)
Note:- If particular DB has different username and password than current DB, you need to change it on the connection URL as well.

Related

How can I save query data from another mongoDB to the collection of DB I am currently connected to?

I've got two databases and I want to write data from another DB in the collection.
I am connected to a mongoDB with
mongoose.connect("mongodb://XXX:YYY#localhost:27017/realtime?authSource=admin"
and writing into a collection based on the Model I currently use.
There is one key-value-pair (it's a timestamp) I need from a different DB which runs on the same port mongodb://XXX:YYY#localhost:27017/timetable?authSource=admin.
Here is a snippet, hope that'll help.
EntityModel
.find({})
.limit(10)
.then((entities) => {
entities.forEach((entity) => {
// this is where I need to access the other DB
// to get arrivalTimetable from the timetable database for Each entity
tripData.stops.push({
stop_id: stu.stopId,
arrivalTimetable: arrivalTimetable,
arrivalRealtime: arrivalRT
});
const tripDelay = new TripDelay(tripData);
trip.save();
}
What is a good way, to get the data needed and save it to the current collection?
$merge allows output to a different database.

Ways to refer to a database, collection, and document in MongoDB?

use <databasename> will set a variable db to be the database
specified by <databasename>, so the database can be referred to
the variable db.
I wonder if a collection or document can also be
referred to by a variable, and if yes, how?
Every object in a MongoDB server has an identifier _id. If I am correct, a database, a collection and a document are objects.
How are the identifier of an object used in practice?
Both a database and a collection have a name. So we can refer to a
collection via its name e.g. mydb.mycollection.
Does a document also have a name?
Thanks.
A collection consists of several documents so a document as such do not have any name. _id distinguishes the documents. To fetch any particular document, you can filter it on the basis of _id or the data stored in it.
Referencing the db and then the collection in selected db will give you the required document.

Is there a way to insert a DB query directly into a new MongoDB on server side?

What I'm trying to do is take a user's query client side (via search function), send it to server via Meteor methods and if there is a search result, insert that query into another MongoDB instance? I need this in order to display search results from the user into client.
Something like this from server side:
UserSearch: function(query){
var init = Table.find({userId: this.userId}, {data: {Name: query}});
Search.insert({userId: this.userId, data: init});
},
Obviously, that doesn't work. But I'm looking for a way to allow to insert a query from one database into a new database.
So I think there are two pieces two your question here:
How do I connect to another MongoDB instance?
How do I insert data from one query result into a collection?
For #1, referencing this SO question, you can do:
var database = new MongoInternals.RemoteCollectionDriver("<mongo url>");
Search = new Mongo.Collection("search", { _driver: database });
For #2, you're simply missing the .fetch() as MasterAM pointed out:
UserSearch: function(query){
var init = Table.find({userId: this.userId, 'data.Name': query}).fetch();
Search.insert({userId: this.userId, data: init});
},
I also modified your Table query a bit as I don't think it's working in the current form. You want each field property in a query object to be in the same object. Note that the fetch will give you an array of Table objects, so you'll need to have your data field in your Search collection reflect that.

How to insert new document only if it doesn't already exist in MongoDB

I have a collection of users with the following schema:
{
_id:ObjectId("123...."),
name:"user_name",
field1:"field1 value",
field2:"field2 value",
etc...
}
The users are looked up by the user.name, which must be unique. When a new user is added, I first perform a search and if no such user is found, I add the new user document to the collection. The operations of searching for the user and adding a new user, if not found, are not atomic, so it's possible, when multiple application servers are connect to the DB server, for two add_user requests to be received at the same time with the same user name, resulting in no such user being found for both add_user requests, which in turn results with two documents having the same "user.name". In fact this happened (due to a bug on the client) with just a single app server running NodeJS and using Async library.
I was thinking of using findAndModify, but that doesn't work, since I'm not simply updating a field (that exists or doesn't exist) of a document that already exists and can use upsert, but want to insert a new document only if the search criteria fails. I can't make the query to be not equal to "user.name", since it will find other users.
First of all, you should maintain a unique index on the name field of the users collection. This can be specified in the schema if you are using Mongoose or by using the statement:
collection.ensureIndex('name', {unique: true}, callback);
This will make sure that the name field remains unique and will solve the problem of concurrent requests as you have specified in your question. You do not require searching when this index is set.

Does not show any collection in mongodb

I am a beginner in mongodb. 2 days before I created a db named inventory and inserted collection too. But today I want get all collections in Inventory
I typed
db.inventory.find()
but it didn't show anything... what's the reason?
If ur db is inventory just use the following commands
use inventory
show collections
This would list u all the collections u've created inside this db .
db.collection_name.find()
will list u all data(documents) u've created in it
In short:
use inventory
show collections
By default the mongo shell connects to the database test. so you have to type use inventory to switch to your desired database (show databases returns a list of all created databases if you are facing errors with typos). After switching to the correct database type show collections to get a list of all created collections in your current database.