- Setup Mongo
- Tools
- Most used commands
- Mongoose
- 4.1 Setting up a Model
- 4.2 create new documents in database
- 4.3 find queries
- 4.4 update queries
- 4.5 others
- export / import databas
See more
Options:
- Mongo Atlas free tier or paid database - registrate and create
- locally installed MongoDB on computer - install
- local MongoDB in docker container - pull from dockerhub (should have Docker Desktop)
Here I use the last option:
docker pull mongo
docker run -p 27018:27017 --name myAppDatabase mongo- Mongo Atlas
Online free MongoDB. It provides also an online interface to browse documents - Mongo Compass
GUI which can connect local and remote Mongo databases. Makes your life easier if you use locally installed or dockerized Mongo
note: I shortened the queries for a better focus, but of course you can always receive return values. You should also use then or await, because a mongo query always returns a thenable object (or a Promise if you use .exec() ).
const allTheFruits = await Fruit.find();- Create multiple documents
Fruit.create(fruitArray);- Function to create one document:
async function newFruit({ name, color, ...optionalFields }) {
Fruit.create({
fruitName: name,
color: color,
...optionalFields,
});
}
await newFruit('orange', 'orange', ')-
Find one item by id:
Fruit.findById(bananaId) -
Find all items in a collection:
Fruit.find() -
Example for find query with filtering:
Customer.find({ $and: [ { $or: [ { Country: "Germany", }, { Country: "France", }, ], }, { VIP: true, }, ], });
-
Filtering options:
- $ne not equal (
!=) - $eq equal (
=) - $gt greater than (
>) - $gte greater or equal than (
>=) - $in in (
in) - $lt less than (
<) - $lte less or equal than (
<=) - $nin not in (
not in)
- $ne not equal (
-
Add an item to a document's field which is an array
const updatedMan = await Man.updateOne( { _id: manId }, { $push: { pastGirlfriends: SusansId } }, done );
Fruit.count();
Fruit.deleteMany();.lean()
mongoexport --uri [mongo db connection url]/[database name] --collection [collection name] --out [filename].jsonmongoimport --uri [mongo db connection url]/[database name] --collection [collection name] --drop --file [filename path].json