Created
July 1, 2021 18:04
-
-
Save keevie/6770dd6aa69b8bfb2cddcd32ac011576 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const test = async () => { | |
| const db = await getConnection(); | |
| const docs = db.collection('docs'); | |
| const doc = { | |
| id: 'test', | |
| list: [ | |
| { id: 2, color: 'red' }, | |
| { id: 1, color: 'green' }, | |
| { id: 3, color: 'blue' }, | |
| ] | |
| } | |
| const query = { id: 'test' } | |
| await docs.updateOne( | |
| query, | |
| { $set: { 'test': doc } }, | |
| { upsert: true } | |
| ); | |
| const arrayFilters = [ | |
| { "elem.id": 1 }, | |
| { "elem1.id": 2 } | |
| ] | |
| const testDoc1 = await docs.findOne({ id: 'test' }) | |
| console.log('test doc before', JSON.stringify(testDoc1, null, 2)) | |
| await docs.updateOne( | |
| query, | |
| { | |
| $set: { | |
| 'test.list.$[elem].color': 'yellow', | |
| 'test.list.$[elem1].color': 'purple', | |
| } | |
| }, | |
| { arrayFilters } | |
| ) | |
| const testDoc2 = await docs.findOne({ id: 'test' }) | |
| console.log('test doc after', JSON.stringify(testDoc2, null, 2)) | |
| } | |
| test() | |
| /// output | |
| test doc before { | |
| "_id": "60ddfef705c9126c2c284c0e", | |
| "id": "test", | |
| "test": { | |
| "id": "test", | |
| "list": [ | |
| { | |
| "id": 2, | |
| "color": "red" | |
| }, | |
| { | |
| "id": 1, | |
| "color": "green" | |
| }, | |
| { | |
| "id": 3, | |
| "color": "blue" | |
| } | |
| ] | |
| } | |
| } | |
| test doc after { | |
| "_id": "60ddfef705c9126c2c284c0e", | |
| "id": "test", | |
| "test": { | |
| "id": "test", | |
| "list": [ | |
| { | |
| "id": 2, | |
| "color": "purple" | |
| }, | |
| { | |
| "id": 1, | |
| "color": "yellow" | |
| }, | |
| { | |
| "id": 3, | |
| "color": "blue" | |
| } | |
| ] | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment