New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

mongo-dot-notation

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mongo-dot-notation - npm Package Compare versions

Comparing version 2.0.0 to 3.0.0

dist/array.d.ts

39

package.json
{
"name": "mongo-dot-notation",
"version": "2.0.0",
"version": "3.0.0",
"description": "Transform objects to mongo update instructions",

@@ -9,3 +9,4 @@ "author": {

},
"main": "./index.js",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"repository": {

@@ -32,17 +33,27 @@ "type": "git",

"license": "MIT",
"readmeFilename": "README.md",
"scripts": {
"test": "mocha",
"ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly",
"coverage": "istanbul cover node_modules/mocha/bin/_mocha --report html",
"lint": "eslint lib"
"prettier": "prettier --check .",
"prettier:fix": "prettier --write .",
"lint": "eslint --ext .ts .",
"lint:fix": "eslint --ext .ts --fix .",
"build": "tsc -p .",
"test": "jest tests/*.spec.ts",
"test:coverage": "jest --coverage tests/*.spec.ts",
"test:e2e": "jest tests/*.e2e.ts",
"test:e2e:docker": "docker-compose up --no-log-prefix --exit-code-from node --attach node"
},
"devDependencies": {
"chai": "^4.2.0",
"eslint": "^6.8.0",
"istanbul": "^0.4.5",
"mocha": "^6.2.2",
"mocha-lcov-reporter": "^1.3.0",
"mongodb": "^3.4.1"
}
"@types/jest": "^28.1.6",
"@types/node": "^16.0.0",
"@typescript-eslint/eslint-plugin": "^5.30.7",
"@typescript-eslint/parser": "^5.30.7",
"eslint": "^8.20.0",
"jest": "^28.1.3",
"mongodb": "^4.8.0",
"prettier": "^2.7.1",
"ts-jest": "^28.0.7",
"ts-node": "^10.9.1",
"typescript": "^4.7.4"
},
"sideEffects": false
}

@@ -1,620 +0,832 @@

mongo-dot-notation
========
Fast, lightweight library to transform objects to mongo update instructions using operators.
# mongo-dot-notation
Transform objects to MongoDB update instructions.
[![NPM Version](https://img.shields.io/npm/v/mongo-dot-notation.svg)](https://npmjs.org/package/mongo-dot-notation)
[![Build Status](https://travis-ci.org/dimadeveatii/mongo-dot-notation.svg?branch=master)](https://travis-ci.org/dimadeveatii/mongo-dot-notation)
[![Coverage Status](https://coveralls.io/repos/github/dimadeveatii/mongo-dot-notation/badge.svg)](https://coveralls.io/github/dimadeveatii/mongo-dot-notation)
[![Build status](https://github.com/dimadeveatii/mongo-dot-notation/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/dimadeveatii/mongo-dot-notation/actions/workflows/ci.yml?query=branch%3Amain++)
[![Coverage Status](https://coveralls.io/repos/github/dimadeveatii/mongo-dot-notation/badge.svg?branch=main)](https://coveralls.io/github/dimadeveatii/mongo-dot-notation?branch=main)
[![Downloads](https://img.shields.io/npm/dm/mongo-dot-notation)](https://npmjs.org/package/mongo-dot-notation)
```javascript
const $ = require('mongo-dot-notation')
```ts
import { flatten, $timestamp, $unset } from 'mongo-dot-notation';
const instructions = $.flatten({
firstName: 'John',
const user = flatten({
firstName: 'Alice',
contact: { phone: '874-478-1254' },
lastUpdate: $.$currentDate()
})
address: {
primary: {
state: 'NY',
nr: 42,
},
},
});
```
/*
const instructions = {
$currentDate: {
lastUpdate: { $type: 'date' }
},
$set: {
'firstName': 'John',
'contact.phone': '874-478-1254'
Sets `user` to:
```json
{
"$set": {
"firstName": "Alice",
"contact.phone": "874-478-1254",
"address.primary.state": "NY",
"address.primary.nr": 42
}
}
*/
```
## Features
## Installation
- Transform objects to `mongo` update instructions
- supports embedded documents
- supports mongo types (`ObjectID`, `Int32` etc.)
- Full support of `mongo` update operators
- `Field` update operators
- `Array` update operators
- `Bitwise` update operators
- Supports Node.js v8 and above
- No `npm` dependencies on `mongo`
```sh
npm install mongo-dot-notation
```
## Usage
## Highlights
Using `$.flatten` and operators to transform to mongo update instructions.
- Fully supported MongoDB [update operators](https://www.mongodb.com/docs/manual/reference/operator/update/)
- _Field_
- _Array_
- _Bitwise_
- No `npm` dependency on `mongo`
- Written in TypeScript
- Type definitions for all exported functions
- Supports flattening and updating array elements by index
```javascript
const $ = require('mongo-dot-notation')
## Usage and examples
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017/db'
const users = (await MongoClient.connect(url)).db.collection('users')
### Using operators to update fields
const updateData = {
comments: $.$push('Logged in.').$each().$slice(-100),
env: 'demo',
login: {
date: $.$currentDate()
```ts
import { flatten, $inc, $currentDate, $push, $setOnInsert } from 'mongo-dot-notation';
const review = {
// Add a comment and keep only the last ten ones
comments: $push('Like it!').$each().$slice(-10),
rating: 10,
counters: {
// increment the `total` by one
total: $inc(),
},
analytics: {
visits: $.$inc()
details: {
// set only if the document is inserted
createdOn: $setOnInsert(new Date()),
// set to current date as a mongo Date
updatedOn: $currentDate(),
},
account: {
createdOn: $.$setOnInsert(new Date()),
blocked: $.$unset(),
attempts: 0,
logins: $.$inc()
}
}
};
await users.update({ _id: 1 }, $.flatten(updateData))
// Provided reviews is a MongoDB collection
await reviews.updateOne(reviewId, flatten(review), { upsert: true });
```
Without `mongo-dot-notation` update instructions should look like:
### Flattening arrays
```javascript
// ...
```ts
import { flatten } from 'mongo-dot-notation';
const updateData = {
$set: {
'env': 'demo',
'account.attempts': 0
},
$push: {
'comments': {
'$each': ['Logged in.'],
'$slice': -100
}
}
$currentDate: {
'login.date': 'date'
},
$inc: {
'analytics.visits': 1,
'account.logins': 1,
},
$unset: {
'account.blocked': ''
},
$setOnInsert: {
'account.createdOn': new Date()
}
}
const user = {
phones: [
{
number: '123-456-789',
primary: true,
},
{
number: '789-012-345',
},
],
};
await users.update({ _id: 1 }, updateData)
// Provided users is a MongoDB collection
await users.updateOne(userId, flatten(user, { array: true }));
```
## Tests
The above `user` object is flattened to:
To run the tests make sure you have mongo 3.0+ installed locally on the default port (*27017*).
`mongo` is used to run integration tests.
Once `mongo` is available, install the dependencies, then run `npm run test`:
```bash
$ npm install
$ npm run test
```json
{
"phones.0.number": "123-456-789",
"phones.0.primary": true,
"phones.1.number": "789-012-345"
}
```
To calculate code coverage run `npm run coverage`.
### Using positional operator
## API
```ts
import { flatten } from 'mongo-dot-notation';
## `.flatten()`
Use `.flatten()` to transform objects:
```javascript
const $ = require('mongo-dot-notation')
const instructions = $.flatten({
account: {
name: 'hero'
}
})
// { '$set': { 'account.name': 'hero' } }
const student = {
grades: $().$inc(),
};
// Finds the element with value 80 in the "grades" array
// and increments it by one.
student.updateOne(
{ _id: 1, grades: 80 },
flatten(student) // { $inc: { "grades.$" : 1 } }
);
```
## `.isOperator()`
Checks if a given value is a `mongo-dot-notation` operator:
```javascript
const $ = require('mongo-dot-notation')
The position operator supports updating a nested document:
$.isOperator(1) // false
$.isOperator({}) // false
$.isOperator($.$set(10)) // true
```ts
import { flatten } from 'mongo-dot-notation';
const student = {
grades: $('value').$inc(),
};
// Finds the document with "value" field equal to 80 in the "grades" array
// and increments it by one.
student.updateOne(
{ _id: 1, grades: 80 },
flatten(student) // { $inc: { "grades.$.value" : 1 } }
);
```
See below the list of all supported mongo update opertors.
To update all elements in a array, use _all positional_ operator:
## Mongo update operators
```ts
import { flatten } from 'mongo-dot-notation';
### Field update operators
const student = {
grades: $('[]').$inc(),
};
#### `.$inc`
See mongo [**$inc**](https://docs.mongodb.com/manual/reference/operator/update/inc/).
The `$inc` operator increments a field by a specified value. If no value is provided, defaults to 1.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
visits: $.$inc(5) // increment current visits value by 5
})
// { '$inc': { 'visits': 5 } }
// Increment all grades by one
student.updateOne(
{ _id: 1 },
flatten(student) // { $inc: { "grades.$[]" : 1 } }
);
```
#### `.$mul`
See mongo [**$mul**](https://docs.mongodb.com/manual/reference/operator/update/mul/).
Similarly, updating nested documents:
Multiplies the value of a field by a number. (*Supported in mongo >= 2.6*)
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
price: $.$mul(0.75) // multiply current price value by 0.75
})
// { '$mul': { 'price': 0.75 } }
```
```ts
import { flatten } from 'mongo-dot-notation';
#### `.$rename`
See mongo [**$rename**](https://docs.mongodb.com/manual/reference/operator/update/rename/).
const student = {
grades: $('[].values').$inc(),
};
The `$rename` operator updates the name of a field.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
nmae: $.$rename('name') // rename nmae field to name
})
// { '$rename': { 'nmae': 'name' } }
// Increment all grades' values by one
student.updateOne(
{ _id: 1 },
flatten(student) // { $inc: { "grades.$[].values" : 1 } }
);
```
#### `.$setOnInsert`
See mongo [**$setOnInsert**](https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/).
### Using filtered positional operator
Assigns value to field only when the document is inserted (when an update operation is with `upsert:true`). (*Supported in mongo >= 2.4*)
```javascript
const $ = require('mongo-dot-notation')
```ts
import { flatten, $mul } from 'mongo-dot-notation';
db.collection('users').update(
{ _id: 1 },
$.flatten({
createdOn: $.$setOnInsert(new Date()) // sets createdOn field only when document is inserted
}),
{ upsert: true })
const student = {
grades: $('[element]').$mul(9),
};
// { '$setOnInsert': { 'createdOn': new Date() } }
// Multiply by ten all grades that are below 9
student.updateOne(
{ _id: 1 },
flatten(student), // { $mul: { "grades.$[element]" : 10 } }
{ arrayFilters: [{ element: { $lte: 9 } }] }
);
```
#### `.$set`
See mongo [**$set**](https://docs.mongodb.com/manual/reference/operator/update/set/).
Similarly, updating nested documents:
The `$set` operator replaces the value of a field with the specified value.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
name: $.$set('Mike')
})
// { '$set': { 'name': 'Mike' } }
```
```ts
import { flatten, $mul } from 'mongo-dot-notation';
The `$set` is an implicit operator, meaning if an object is passed to `$.flatten`, it will navigate through own and embedded document fields and apply $set.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
name: 'Mike',
contactDetails: {
email: 'mike@test.com'
}
})
const student = {
grades: $('[element].value').$mul(9),
};
// {
// '$set': {
// 'name': 'Mike',
// 'contactDetails.email': 'mike@test.com'
// }
// }
// Multiply by ten all grades that are below 9
student.updateOne(
{ _id: 1 },
flatten(student), // { $mul: { "grades.$[element].value" : 10 } }
{ arrayFilters: [{ element: { $lte: 9 } }] }
);
```
The `$set` operator could also be used to update an embedded document entirely:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
name: 'Mike',
// contactDetails is updated to a new document
contactDetails: $.$set({
email: 'mike@test.com'
})
})
See the [end-to-end](tests/mongo.e2e.ts) tests file for more examples.
// {
// '$set': {
// 'name': 'Mike',
// 'contactDetails': { email: 'mike@test.com' }
// }
// }
```
## API
#### `.$unset`
See mongo [**$unset**](https://docs.mongodb.com/manual/reference/operator/update/unset/).
**Table of contents**
The `$unset` operator deletes a particular field.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
comments: $.$unset(), // remove field from document
history: $.$unset()
})
// { '$unset': { 'comments': '', 'history': '' } }
```
- [Options](#options)
- [flatten](#flatten)
- [isOperator](#isOperator)
#### `.$min`
See mongo [**$min**](https://docs.mongodb.com/manual/reference/operator/update/min/).
- [Field update operators](#field-update-operators)
The `$min` updates the value of the field to a specified value if the specified value is less than the current value of the field.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
low: $.$min(200) // update low to 200 if current low value is greater than 200
})
// { '$min': { 'low': 200 } }
```
- [$currentDate](#currentdate)
- [$timestamp](#timestamp)
- [$inc](#inc)
- [$min](#min)
- [$max](#max)
- [$mul](#mul)
- [$rename](#rename)
- [$set](#set)
- [$setOnInsert](#setoninsert)
- [$unset](#unset)
#### `.$max`
See mongo [$max](https://docs.mongodb.com/manual/reference/operator/update/max/).
- [Array update operators](#array-update-operators)
The `$max` operator updates the value of the field to a specified value if the specified value is greater than the current value of the field.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
high: $.$max(450) // update high to 450 if current high value is less than 450
})
// { '$max': { 'high': 450 } }
- [$](#-positional)
- [$addToSet](#addtoset)
- [$pop](#pop)
- [$pull](#pull)
- [$push](#push)
- [$pullAll](#pullall)
- [$slice](#slice)
- [$sort](#sort)
- [Bitwise update operators](#bitwise-update-operators)
- [$bit](#bit)
- [$and](#and)
- [$or](#or)
- [$xor](#xor)
### Options
The following options are available:
| Option | Description |
| ------------------ | --------------------------------------------------------------------------------------------- |
| `array` | _(default `false`)_ if true, arrays will be flattened and their indexes will be used as keys. |
| `skipEmptyObjects` | _(default `false`)_ if true, empty objects are ignored and removed from the flattened result. |
**Example:**
```ts
flatten({ rules: [{ value: 7 }] }, { array: true });
// { $set: { 'rules.0.value': 7 } }
flatten({ rules: [{ value: 7 }] }, { array: false });
// { $set: { 'rules': [{value: 7}] } }
flatten({ left: { x: 1 }, right: {} }, { skipEmptyObjects: true });
// { $set: { 'left.x': 1 } }
flatten({ left: { x: 1 }, right: {} }, { skipEmptyObjects: false });
// { $set: { 'left.x': 1, 'right': {} } }
```
#### `.$currentDate`
See mongo [**$currentDate**](https://docs.mongodb.com/manual/reference/operator/update/currentDate/).
### flatten
The `$currentDate` operator sets the value of a field to the current date, either as a *Date* or a *Timestamp*.
If type is not specified, uses *Date* by default.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
lastUpdate: $.$currentDate()
})
// { '$currentDate': { 'lastUpdated': { '$type': 'date' } } }
> `$flatten<T>(obj: T, options?: Options)`
Transforms a given object into the MongoDB's update instructions.
| Option | Description |
| ------- | -------------------------------------------------------- |
| obj | _(required)_ the input object to transform |
| options | _(optional)_ additional options, see [Options](#options) |
**Example:**
```ts
flatten({
firstName: 'Alice',
contact: { phone: '874-478-1254' },
address: {
primary: {
state: 'NY',
nr: 42,
},
},
});
```
To set as a timestamp, use:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
lastUpdate: $.$currentDate('timestamp')
})
// { '$currentDate': { 'lastUpdated': { '$type': 'timestamp' } } }
### isOperator
> `isOperator<T>(obj: T): boolean`
Checks if a given object is an operator.
**Example:**
```ts
isOperator($set(1)); // true
isOperator({}); // false
```
Also, for timestamp an alias operator is defined in `mongo-dot-notation`:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
lastUpdate: $.$timestamp()
})
// { '$currentDate': { 'lastUpdated': { '$type': 'timestamp' } } }
---
### Field update operators
### $currentDate
> `$currentDate(type?: 'date' | 'timestamp')`
| Param | Description |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | _(default `date`)_ sets to MongoDB's [Date](https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-document-bson-type-date) or [Timestamp](https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-document-bson-type-timestamp) type. |
Sets the value of a field to the current date.
**Example:**
```ts
flatten({
createdOn: $currentDate(),
});
```
### Array update operators
#### `.$ (update)`
See mongo [**$ (update)**](https://docs.mongodb.com/manual/reference/operator/update/positional/).
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/currentDate/)
The positional `$` operator identifies an element in an array to update without explicitly specifying the position of the element in the array.
```javascript
const $ = require('mongo-dot-notation')
db.students.update(
{ _id: 1, grades: 80 }, // match all elements from grades array where value equals to 80
$.flatten({
grades: $.$().$set(82) // for matched elements, update value to 82
})
)
// { $set: { "grades.$" : 82 } }
### $timestamp
> `$timestamp()`
Sets the value of a field to the current date as a MondoDB's [Timestamp](https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-document-bson-type-timestamp) type.
This function is an alias for `$currentDate('timestamp')`.
**Example:**
```ts
flatten({
updatedOn: $timestamp(),
});
```
In order to update the matched document's field:
```javascript
const $ = require('mongo-dot-notation')
db.students.update(
{ _id: 1, 'grades.grade': 80 },
$.flatten({
grades: $.$('std').$set(1.5)
})
)
// { $set: { "grades.$.std" : 1.5 } }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/currentDate/)
### $inc
> `$inc<T>(value?: T)`
Increments a field by a specified value.
| Param | Description |
| ----- | ----------------------------- |
| value | _(default 1)_ increment value |
**Example:**
```ts
flatten({
visits: $inc(),
clicks: $inc(5),
});
```
The positional `$` operator is chainable with all mongo supported update fields.
```javascript
const $ = require('mongo-dot-notation')
db.students.update(
{ _id: 1, grades: 80 },
$.flatten({
grades: $.$().$mul(0.1) // multiplies matched array element by 0.1
})
)
// { $mul: { "grades.$" : 0.1 } }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/inc/)
### $min
> `$min<T>(value: T)`
Updates the value of the field to a specified value if the specified value is **less than** the current value of the field.
| Param | Description |
| ----- | ---------------------- |
| value | _(required)_ min value |
**Example:**
```ts
flatten({
score: $min(100),
});
```
Can also be used to update an array element by a given index:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
grades: $.$(0).$set(100)
})
// { $set: { "grades.0" : 0.1 } }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/min/)
### $max
> `$max<T>(value: T)`
Updates the value of the field to a specified value if the specified value is **greater than** the current value of the field.
| Param | Description |
| ----- | ---------------------- |
| value | _(required)_ max value |
**Example:**
```ts
flatten({
score: $max(0),
});
```
Same, when updating the element's field:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
months: $.$('5.avgTemp').$set(25.7)
})
// { $set: { "months.5.avgTemp" : 25.7 } }
```
#### `.$addToSet`
See mongo [**$addToSet**](https://docs.mongodb.com/manual/reference/operator/update/addToSet).
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/max/)
The `$addToSet` operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
values: $.$addToSet(5)
})
// { '$addToSet': { 'values': 5 } }
### $mul
> `$mul<T>(value?: T)`
Multiplies the value of a field by a number.
| Param | Description |
| ----- | ----------------------------- |
| value | _(default 1)_ multiply factor |
**Example:**
```ts
flatten({
score: $mul(2.5),
});
```
To add each value from a given array:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
values: $.$addToSet([7, 1, 4]).$each()
})
// { '$addToSet': { 'values': { '$each': [7, 1, 4] } } }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/max/)
### $rename
> `$rename(field: string)`
Updates the name of a field.
| Param | Description |
| ----- | --------------------------- |
| field | _(required)_ new field name |
**Example:**
```ts
flatten({
profile: {
first_name: $rename('firstName'),
},
});
```
#### `.$pop`
See mongo [**$pop**](https://docs.mongodb.com/manual/reference/operator/update/pop).
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/rename/)
The `$pop` operator removes the first or last element of an array. Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
values: $.$pop() // removes by default last element
})
// { '$pop': { 'values': 1 } }
### $set
> `$set<T>(value: T)`
Replaces the value of a field with the specified value.
This is an implicit operator, but could be useful when an entire object should be replaced.
| Param | Description |
| ----- | ------------------------------ |
| value | _(required)_ replacement value |
**Example:**
```ts
// Replaces the address object entirely rather than just
// updating the "city" field.
flatten({
address: $set({ city: 'NY' }),
profile: { name: 'Alice' },
});
// Outputs:
// {
// "$set": {
// "address": { "city": "NY" },
// "profile.name": "Alice"
// }
// }
```
To remove first element from the array:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
values: $.$pop(-1)
})
// { '$pop': { 'values': -1 } }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/set/)
### $setOnInsert
> `$setOnInsert<T>(value: T)`
Assigns the specified value to the field when `{ upsert: true }` operation is used and
results in a new document being created. If the update operation does not result in an insert,
does nothing.
| Param | Description |
| ----- | -------------------------------------------------- |
| value | _(required)_ the value to set on document creation |
**Example:**
```ts
flatten({
logging: {
createdOn: $setOnInsert(new Date()),
},
});
```
There are chainable `.first()` and `.last()` methods defined:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
indexes: $.$pop().first(),
scores: $.$pop().last(),
})
// { '$pop': { 'indexes': -1, scores: 1 } }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/setOnInsert/)
### $unset
> `$unset()`
Deletes the specified field from a document.
**Example:**
```ts
flatten({
resetPassword: $unset(),
});
```
#### `.$pullAll`
See mongo [**$pullAll**](https://docs.mongodb.com/manual/reference/operator/update/pullAll/).
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/unset/)
The `$pullAll` operator removes all instances of the specified values from an existing array.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
values: $.$pullAll([0, 1])
})
// { '$pullAll': { 'values': [0, 1] } }
---
### Array update operators
### $ _(positional)_
> `$(field?: number | string)`
The positional operator identifies **an element** or **multiple elements** matching a
given query condition to be updated in an array.
| Param | Description |
| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| field | _(optional)_ when empty - performs the update on array's element, when a number or a string starting with a number - specifies the index of the element to update or its field, when starts with "[]" or "[query]" specifies that this is an _all positional_ operator |
**Example:**
```ts
// Sets to 7 first element that matches the update query
$().$set(7);
// Increment by one the first element's `score` field that matches the update query
$('score').$inc(1);
// Multiplies all elements by two
$('[]').$mul(2);
// Ensures all elements in array are positive
$('[].score').$max(0);
// Find all `grades` documents that have the `std` lower than seven
// and increment their `grade` by ten.
collection.updateOne(criteria, flatten({ grades: $('[element].grade').$inc(10) }), {
arrayFilters: [{ 'element.std': { $lt: 7 } }],
});
```
#### `.$pull`
See mongo [**$pull**](https://docs.mongodb.com/manual/reference/operator/update/pull/).
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/positional/)
The `$pull` operator removes from an existing array all instances of a value or values that match a specified condition.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
values: $.$pull(7)
})
// { '$pull': { 'values': 7 } }
### $addToSet
> `$addToSet<T>(value: T | T[])`
Adds a value to an array unless the value is already present.
To add multiple values, chain with `$each` operator.
| Param | Description |
| ----- | ---------------------------------------- |
| value | _(required)_ the value to add to the set |
Note that while `$addToSet([1, 2])` adds the entire array as single element,
`$addToSet([1, 2]).$each()` adds 1 and 2 as separate elements.
**Example:**
```ts
// add just one element
flatten({ permissions: $addToSet('admin') });
// add multiple elements
flatten({ permissions: $addToSet(['read', 'write']).$each() });
```
If an array is provided, implicitly applies `$in` operator:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
values: $.$pull([0, 1])
})
// { '$pull': { 'values': { '$in': [0, 1] } } }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/)
### $pop
> `$pop(value?: -1 | 1)`
Removes the first or last element of an array
| Param | Description |
| ----- | -------------------------------------------------------------------------------------- |
| value | _(default 1)_ specify `-1` to remove the first element, `1` to remove the last element |
**Example:**
```ts
// remove the first element from the array
flatten({ grades: $pop(-1) });
// equivalent to:
flatten({ grades: $pop().first() });
```
See mongo documentation for [conditions](https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-all-items-that-match-a-specified-pull-condition).
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/pop/)
#### `.$push`
See mongo [**$push**](https://docs.mongodb.com/manual/reference/operator/update/push/).
### $pull
The `$push` operator appends a specified value to an array. Can also be used to slice and sort the array.
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
grades: $.$push({ grade: 'A' })
})
// { '$push': { 'grades': { grade: 'A' } } }
> `$pull<T>(value: T | T[])`
Removes from an existing array all instances of a value or values that match a specified condition.
Unlike the [$pullAll](#pullall) operator, this operator can be used to remove all instances that match a query.
| Param | Description |
| ----- | ------------------------------------------------------------------------ |
| value | _(required)_ the value(s) or condition to match to remove from the array |
**Example:**
```ts
// remove all instances of the value `0` and `1` from the array;
// same as using $pullAll
flatten({ scores: $pull([0, 1]) });
// remove all instances lower than or equal to `3`
flatten({ scores: $pull({ $lte: 3 }) });
// remove all documents with the field `name` equal to `Test`
flatten({ users: $pull({ name: { $eq: 'Test' } }) });
```
To push several values, chain with `.$each()`
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
grades: $.$push([{ grade: 'A' }, { grade: 'B' }]).$each()
})
// {
// '$push': {
// 'grades': {
// '$each': [{ grade: 'A' }, { grade: 'B' }]
// }
// }
// }
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/pull/)
### $push
> `$push<T>(value?: T | T[])`
Appends a specified value to an array.
Can be chained with `.$slice()`, `.$sort()` and `.$position()` modifiers to specify how the array should be updated.
The order in which additional operators are chained doesn't matter, so that `$push().$each().$slice().$sort()` is the same as
`$push().$each().$sort().$slice()`.
| Param | Description |
| ----- | ------------------------------------------------ |
| value | _(optional)_ the value(s) to append to the array |
**Example:**
```ts
// append one element
flatten({ scores: $push(1) });
// append multiple elements
flatten({ scores: $push([1, 2, 3]).$each() });
// append an element and update to leave only the last ten
flatten({ scores: $push(7).$each().$slice(-10) });
// append an element and update to leave only the last ten sorted by value
flatten({ scores: $push(7).$each().$sort(1).$slice(-10) });
// append an element at position three in the array
flatten({ scores: $push(7).$each().$position(2) });
```
To push values at a specific position use `.$position()` (*requires the use of .$each(). Supported in mongo >= 2.6*)
```javascript
const $ = require('mongo-dot-notation')
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/push/)
// insert as a first element in the array
$.flatten({
grades: $.$push({ grade: 'A' }).$each().$position(0)
})
// {
// '$push': {
// 'grades': {
// '$each': [{ grade: 'A' }],
// '$position': 0
// }
// }
// }
### $pullAll
> `$pullAll<T>(value: T | T[])`
Removes all instances of the specified values from an existing array.
| Param | Description |
| ----- | -------------------------------------------------- |
| value | _(required)_ the value(s) to remove from the array |
**Example:**
```ts
// remove all instances of the value `1` and `2` from the array
flatten({ score: $pullAll([1, 2]) });
// remove all instances of the value `0`
flatten({ score: $pullAll(0) });
```
To slice the array, use `.slice()` (*requires the use of .$each(). Supported in mongo >= 2.6*)
```javascript
const $ = require('mongo-dot-notation')
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/pullAll/)
// insert the element and limit to last 10 values
$.flatten({
grades: $.$push({ grade: 'A' }).$each().$slice(-10)
})
// {
// '$push': {
// 'grades': {
// '$each': [{ grade: 'A' }],
// '$slice': -10
// }
// }
// }
### $slice
> `$slice(count: number)`
Limits the number of array elements.
Alias for `$push().$each().$slice()`.
| Param | Description |
| ----- | --------------------------------------- |
| count | _(required)_ number of elements to take |
**Example:**
```ts
// leave only the first 3 elements
flatten({ grades: $slice(3) });
// leave only the last element
flatten({ grades: $slice(-1) });
// empty the array
flatten({ grades: $slice(0) });
```
To sort the array, use `.sort()` (*requires the use of .$each(). Supported in mongo >= 2.4*)
```javascript
const $ = require('mongo-dot-notation')
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/slice/)
// insert the element and sorts descending by grade
$.flatten({
grades: $.$push({ grade: 'A' }).$each().$sort({ grade: -1})
})
// {
// '$push': {
// 'grades': {
// '$each': [{ grade: 'A' }],
// '$sort': { grade: -1}
// }
// }
// }
### $sort
> `$sort<T>(specification?: T)`
Orders the elements of an array.
Alias for `$push().$each().$sort()`.
| Param | Description |
| ------------- | -------------------------------- |
| specification | _(default 1)_ sort specification |
**Example:**
```ts
// sort ascending
flatten({ scores: $sort(1) });
// sort descending
flatten({ scores: $sort(-1) });
// sort ascending an array of documents with `name` field
flatten({ users: $sort({ name: 1 }) });
```
Multiple instructions can be chained:
```javascript
const $ = require('mongo-dot-notation')
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/sort/)
// insert the element, sorts descending by grade
// and slices only first 10 values
$.flatten({
grades: $.$push({ grade: 'A' }).$each().$sort({ grade: -1}).$slice(10)
})
// {
// '$push': {
// 'grades': {
// '$each': [{ grade: 'A' }],
// '$sort': { grade: -1},
// '$slice': 10
// }
// }
// }
---
### Bitwise update operators
### $bit
> `$bit()`
Performs a bitwise update of a field.
Should be chained with the a logical operator.
**Example:**
```ts
flatten({
admin: $bit().$and(7),
read: $bit().$or(4),
write: $bit().$xor(3),
});
```
In case the array needs only to be sorted and/or sliced, `mongo-dot-notation` defines aliases:
```javascript
const $ = require('mongo-dot-notation')
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/bit/)
$.flatten({
grades: $.$sort({ grade: 1 }), // sames as $.push([]).$each().$sort({ grade: 1 })
scores: $.$slice(10), // sames as $.push([]).$each().$slice(1)
values: $.$sort().$slice(-5) // sames as $.push([]).$each().$sort().$slice(-5)
})
### $and
> `$and<T>(value: T)`
Uses a bitwise _and_ operation to update a field.
Alias for `$bit().$and()`.
**Example:**
```ts
flatten({
admin: $and(7),
});
```
### Bitwise update operators
#### `.$bit`
See mongo [**$bit**](https://docs.mongodb.com/manual/reference/operator/update/bit/).
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/bit/#bitwise-and)
The `$bit` operator performs a bitwise update of a field. The operator supports bitwise AND, bitwise OR, and bitwise XOR (i.e. exclusive or) operations.
*Note XOR is supported in mongo >= 2.6*
### $or
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
owner: $.$bit().$and(7) // performs a bitwise AND
user: $.$bit().$or(1) // performans a bitwise OR
group: $.$bit().$xor(5) // performs a bitwise XOR
})
> `$or<T>(value: T)`
// {
// '$bit': {
// 'owner': { and: 7 },
// 'user': { or: 1 },
// 'group': { xor: 5 },
// }
// }
Uses a bitwise _or_ operation to update a field.
Alias for `$bit().$or()`.
**Example:**
```ts
flatten({
read: $or(4),
});
```
Following aliases are defined in `mongo-dot-notation`:
```javascript
const $ = require('mongo-dot-notation')
$.flatten({
owner: $.$and(7), // same as $.$bit().$and(7)
user: $.$or(1), // same as $.$bit().$or(1)
group: $.$xor(5), // same as $.$bit().$xor(5)
})
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/bit/#bitwise-or)
### $xor
> `$xor<T>(value: T)`
Uses a bitwise _xor_ operation to update a field.
Alias for `$bit().$xor()`.
**Example:**
```ts
flatten({
write: $xor(3),
});
```
[MongoDB manual](https://www.mongodb.com/docs/manual/reference/operator/update/bit/#bitwise-xor)
## License
[MIT](LICENSE)
[MIT](LICENSE)

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc