MongoDB: Operators

List of comparison operators: $cmp, $eq, $gt, $gte, $lt, $lte, and $ne




retrieve documents in a collection using Boolean conditions (Query Operators)

//AND

db.collection.find( {

$and: [

{ key: value }, { key: value }

]

})

//OR

db.collection.find( {

$or: [

{ key: value }, { key: value }

]

})

//NOT

db.inventory.find( { key: { $not: value } } )




 You can use other operators besides $set when updating a document. The $push operator allows

you to push a value into an array, in this case we will add a new nickname to the nicknames array.

db.people.update({name: 'Tom'}, {$push: {nicknames: 'Tommy'}})

// This adds the string 'Tommy' into the nicknames array in Tom's document.

The $pull operator is the opposite of $push, you can pull specific items from arrays.

db.people.update({name: 'Tom'}, {$pull: {nicknames: 'Tommy'}})

// This removes the string 'Tommy' from the nicknames array in Tom's document.

The $pop operator allows you to remove the first or the last value from an array. Let's say Tom's

document has a property called siblings that has the value ['Marie', 'Bob', 'Kevin', 'Alex'].

db.people.update({name: 'Tom'}, {$pop: {siblings: -1}})

// This will remove the first value from the siblings array, which is 'Marie' in this case.

db.people.update({name: 'Tom'}, {$pop: {siblings: 1}})

// This will remove the last value from the siblings array, which is 'Alex' in this case.


db.student.update(

{name: 'Tom'}, // query criteria

{$set: {age: 22}} // update action

);


Delete


Delete

Deletes all documents matching the query parameter:


db.people.deleteMany({name: 'Tom'})

// All versions

db.people.remove({name: 'Tom'})

Or just one

// New in MongoDB 3.2

db.people.deleteOne({name: 'Tom'})

// All versions

db.people.remove({name: 'Tom'}, true)

MongoDB's remove() method. If you execute this command without any argument or without empty

argument it will remove all documents from the collection.

db.people.remove();

or

db.people.remove({});

Comments

Popular posts from this blog

AIDS Meanstack Sample questions

Express.js Registration form data 2 Server