0

A query to how to update the items array of object by

  • finding the breed dachshund
  • update the name to new-dog
  • updatedAt to the current time
[{
    "_id" : ObjectId("60053b74aa72f132cb75b8b6"),
    "clientId" : "test",
    "items" : [ 
        {
            "_id" : ObjectId("60053b74aa72f132cb75b8b7"),
            "name" : "tommy",
            "breed" : "dachshund",
            "createdAt" : 1610955636,
            "updatedAt" : 1610955636
        }, 
        {
            "_id" : ObjectId("60053b74aa72f132cb75b8b8"),
            "name" : "mickey",
            "breed" : "husky",
            "createdAt" : 1610955636,
            "updatedAt" : 1610955636
        }, 
        {
            "_id" : ObjectId("60053b74aa72f132cb75b8b9"),
            "name" : "whiskey",
            "breed" : "dachshund",
            "createdAt" : 1610955636,
            "updatedAt" : 1610955636
        }, 
        {
            "_id" : ObjectId("60053b74aa72f132cb75b8ba"),
            "name" : "milo",
            "breed" : "bulldog",
            "createdAt" : 1610955636,
            "updatedAt" : 1610955636
        }, 
        {
            "_id" : ObjectId("60053b74aa72f132cb75b8bb"),
            "name" : "pooh",
            "breed" : "poodle",
            "createdAt" : 1610955636,
            "updatedAt" : 1610955636
        }
    ],
    "shopname" : "myshopify"
}]
3
  • Could you please show your try, you can use update command with arrayFilters. Commented May 13, 2021 at 18:44
  • model.updateOne({_id: ObjectId("60053b74aa72f132cb75b8b6")}, {arrayFilters: [{'el.breed': 'dachshund'}]},{$set: {'items.name': 'new-dog'}}) Commented May 13, 2021 at 18:46
  • You query is not valid, you can read documentation, see similar Update nested array objects based on a property in MongoDB this might help you. Commented May 13, 2021 at 18:56

1 Answer 1

0
const curDatetime = moment(moment();

model.updateOne(
{_id: ObjectId("60053b74aa72f132cb75b8b6")}, 
{
   arrayFilters: [
     {'el.breed': 'dachshund'}
   ]
},
{
   $set: {
     'items.$[el].name': 'new-dog',
     'items.$[el].updatedAt': curDatetime
   }
}, "multi": true)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.