Skip to content

Instantly share code, notes, and snippets.

@keevie
Created July 1, 2021 18:04
Show Gist options
  • Select an option

  • Save keevie/6770dd6aa69b8bfb2cddcd32ac011576 to your computer and use it in GitHub Desktop.

Select an option

Save keevie/6770dd6aa69b8bfb2cddcd32ac011576 to your computer and use it in GitHub Desktop.
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