MongoDb findOneAndUpdate does not update specific document - node.js

I'm having trouble getting and updating the only document that matches filter in nest array of objects in mongoose, I'm using the findOneAndUpdate query in mongoose.
This is my data:
{
"_id": "62e87e193fe01f5068f9ae11",
"year": "2023",
"month": "1",
"department_id":"62e387d39ffb6ada6c590fbf",
"blocks": [
{
"name": "CEEDO Schedule Block",
"days": [
{
"day": 2,
"employees": [
{
"employee_id":"62cf92fb3a790000170062e3",
"schedule_type": "Day Off"
},
{
"employee_id": "62cf92fb3a790000170062e2",
"schedule_type": "Shifting"
},
{
"employee_id": "62cf92fb3a790000170062e4",
"schedule_type": "Regular"
}
],
"_id": "62e87e193fe01f5068f9ae13"
},
{
"day": 6,
"employees": [
{
"employee_id": "62cf92fb3a790000170062e3",
"schedule_type": "Day Off"
},
{
"employee_id": "62cf92fb3a790000170062e2",
"schedule_type": "Shifting"
},
{
"employee_id":"62cf92fb3a790000170062e4",
"schedule_type": "Regular"
}
],
"_id": "62e87e193fe01f5068f9ae14"
}
],
"_id": "62e87e193fe01f5068f9ae12"
}
]
}
And here is my query:
const update_block = await schedule_model.findOneAndUpdate({'blocks.days._id': '62e87e193fe01f5068f9ae13'},
{
$set: {"days":req.body.days, "employees":req.body.employees}
}
);
Thanks in advance.

try change '62e87e193fe01f5068f9ae13' to mongoose.Types.ObjectId('62e87e193fe01f5068f9ae13')

I finally found the answer by using the arrayFilter function in mongoose:
const update_block = await schedule_model.updateOne({
"_id": mongoose.Types.ObjectId('62e87e193fe01f5068f9ae11')
}, {
"$set": {
"blocks.$[i].days.$[j].day": 31
}
}, {
arrayFilters: [{
"i._id":mongoose.Types.ObjectId('62e87e193fe01f5068f9ae12')
}, {
"j._id": mongoose.Types.ObjectId('62e87e193fe01f5068f9ae14')
}]
})
console.log(update_block)
Thank you.

Related

How to only update one match of an array filter in mongodb

Problem:
I need to only update one document in the spots available array that has an id of "empty". My previous query was updating all matching sub documents with "empty" as the id; which is no good Example Below. So I decided to use aggregation so that I could add a limit stage so that I could only update one item, but come to find out I cannot update the original document with an aggregation. This leaves the only option to use an array filter that only updates one/first of its matches. Is this possible? I feel like there has to be a way to only update one match on an array filter and if there isn't this is definitely something that should be added.
My code:
This code updates every object with "empty"
const client = await clientPromise;
const db = client.db();
// const query = db.collection('events').aggregate(agg);
const query = await db.collection('events').updateOne({
_id: new ObjectId("6398c34ca67dbe3286452f23"),
createdBy: new ObjectId("636c1778f1d09191074f9690"),
"weights.weight": 12
},
{
$set: {
"weights.$.spotsAvailable.$[el2]": {
"name": "Wayne Wrestler",
"userId": new ObjectId("636c1778f1d09191074f9690")
}
}
},
{
arrayFilters: [{ "el2": { "userId": "empty" } }]
})
Example documents:
Event:
{
"_id": {
"$oid": "6398c34ca67dbe3286452f23"
},
"name": "test",
"createdBy": {
"$oid": "636c1778f1d09191074f9690"
},
"description": "testing",
"date": {
"$date": {
"$numberLong": "1645488000000"
}
},
"location": {
"type": "Point",
"coordinates": [
0,
0
]
},
"weights": [
{
"spotsAvailable": [
{
"name": "empty",
"userId": "empty"
},
{
"name": "empty",
"userId": "empty"
},
{
"name": "empty",
"userId": "empty"
}
],
"weight": 12
},
{
"spotsAvailable": [
{
// only one of these should've been updated, but both were
"name": "Wayne Wrestler",
"userId": {
"$oid": "636c1778f1d09191074f9690"
}
},
{
"name": "Wayne Wrestler",
"userId": {
"$oid": "636c1778f1d09191074f9690"
}
}
],
"weight": 15
}
],
"eventApplicants": [
{
"userId": {
"$oid": "636c1778f1d09191074f9690"
},
"name": "Wayne Wrestler",
"weight": 12
}
]
}
User:
{
"_id": {
"$oid": "636c1778f1d09191074f9690"
},
"name": "Wayne Wrestler",
"email": "wakywayne80#gmail.com",
"image": "https://lh3.googleusercontent.com/a/ALm5wu32gXjDIRxncjjQA9I4Yl-sjFH5EWsTlmvdM_0kiw=s96-c",
"emailVerified": {
"$date": {
"$numberLong": "1670864727212"
}
},
"createdEvents": [
{
"createdEventName": "test",
"createdEventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"createdEventDescription": "testing",
"createdEventWeights": [
{
"weight": "12",
"filled": [
false,
false,
false
]
},
{
"weight": "15",
"filled": [
false,
false
]
}
],
"createdEventId": {
"$oid": "6398c34ca67dbe3286452f23"
}
}
],
"userSignedUpEvents": [],
"availableWeights": [
1,
123
],
"signedUpEvents": [
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "637ec484ac2d675b30590b47"
},
"eventName": "Maybe?",
"eventDate": {
"$date": {
"$numberLong": "1672272000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "638d5274628db2a7bf61df49"
},
"eventName": "Eva's",
"eventDate": {
"$date": {
"$numberLong": "1698019200000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398a922abb5c168ede595fb"
},
"eventName": "Nikko's event",
"eventDate": {
"$date": {
"$numberLong": "1670976000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398a922abb5c168ede595fb"
},
"eventName": "Nikko's event",
"eventDate": {
"$date": {
"$numberLong": "1670976000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
}
]
}
I have tried:
Pluging in variables without the new ObjectId syntax
Plugin in variables with the new ObjectId syntax
Using the exact same hardcoded values that I got from copying the aggregation code from compass for the node driver
All of these either don't work or result in every subdocument with "empty" getting filled
One option is to use update with pipeline:
Since this is a double nested array, it is easier to do it in two steps - internal and external
First create the "external" item to replace in weights array and call it newItem. It is calculated using $reduce which allow us to manipulate the internal array while looping on it.
Replace the relevant item on weights array with our newItem using $map with $cond
db.collection.update(
{_id: ObjectId("6398c34ca67dbe3286452f23"), "weights.weight": 12},
[
{$set: {
newItem: {$reduce: {
input: {$getField: {
input: {$first: {
$filter: {
input: "$weights",
as: "item",
cond: {$eq: ["$$item.weight", 12]}
}
}},
field: "spotsAvailable"
}},
initialValue: [],
in: {$concatArrays: [
"$$value",
{$cond: [
{$and: [
{$eq: ["$$this.userId", "empty"]},
{$not: {$in: [ObjectId("636c1778f1d09191074f9690"), "$$value.userId"]}}
]},
[{
name: "Wayne Wrestler",
userId: ObjectId("636c1778f1d09191074f9690")
}],
["$$this"]
]}
]}
}}
}},
{$set: {
weights: {$map: {
input: "$weights",
in: {$cond: [
{$eq: ["$$this.weight", 12]},
{$mergeObjects: [
"$$this",
{spotsAvailable: "$newItem"}
]},
"$$this"
]}
}},
newItem: "$$REMOVE"
}}
])
See how it works on the playground example
You can first $unwind the weights for easier processing first. Use $reduce to iterate through the weights.spotsAvailable array and use a compound object to store the result and a flag to indicate whether it is updated or not. Finally use the result to $merge back to the original document.
db.collection.aggregate([
{
$match: {
"_id": ObjectId("6398c34ca67dbe3286452f23"),
createdBy: ObjectId("636c1778f1d09191074f9690"),
"weights.weight": 12,
"weights.spotsAvailable.userId": "empty"
}
},
{
"$unwind": "$weights"
},
{
"$addFields": {
"results": {
"$reduce": {
"input": "$weights.spotsAvailable",
"initialValue": {
result: [],
updated: false
},
"in": {
"$cond": {
"if": {
$and: [
{
$eq: [
false,
"$$value.updated"
]
},
{
$eq: [
"empty",
"$$this.userId"
]
}
]
},
"then": {
result: {
"$concatArrays": [
"$$value.result",
[
{
"name": "Wayne Wrestler",
"userId": ObjectId("636c1778f1d09191074f9690")
}
]
]
},
updated: true
},
"else": {
result: {
"$concatArrays": [
"$$value.result",
[
"$$this"
]
]
},
updated: "$$value.updated"
}
}
}
}
}
}
},
{
$set: {
"weights.spotsAvailable": "$results.result",
"results": "$$REMOVE"
}
},
{
$group: {
_id: "$_id",
"name": {
$first: "$name"
},
"createdBy": {
$first: "$createdBy"
},
"description": {
$first: "$description"
},
"date": {
$first: "$date"
},
"location": {
$first: "$location"
},
"weights": {
$push: "$weights"
},
"eventApplicants": {
$first: "$eventApplicants"
}
}
},
{
"$merge": {
"into": "collection",
"on": "_id"
}
}
])
Mongo Playground

How to use aggregation with nested document?

I'm new to mongoose, I'm confuse while create the query. Can you help me?
I have a movie document like this :
"movies": [
{
"id": "635611395a71beb6c5bf0b4d",
"title": "Mission: Impossible - Fallout",
"createdAt": "2022-10-24T04:14:54.445Z",
"cast": [
{
"actor": "635350c581d5b60383f0c4be",
"roleAs": "Ethan Hunt",
"leadActor": true,
"_id": "635658c18b9e50facd7f1fd1"
},
{
"actor": "63560bf55a71beb6c5bf0b1f",
"roleAs": "Ilsa Faust",
"leadActor": false,
"_id": "635658c18b9e50facd7f1fd2"
}
],
"poster": {
"url": "https://res.cloudinary.com/debfn35m1/image/upload/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"public_id": "vczxb7lgbonjn8ydsyep",
"responsive": [
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_640/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_50/v1666603204/vczxb7lgbonjn8ydsyep.jpg"
]
},
"reviews": {
"ratingAvg": "5.0",
"reviewCount": 2
}
},
{
"id": "635614855a71beb6c5bf0bdc",
"title": "Spider-Man: No Way Home",
"createdAt": "2022-10-24T04:28:58.286Z",
"cast": [
{
"actor": "635350a881d5b60383f0c4b8",
"roleAs": "Peter Parker",
"leadActor": true,
"_id": "636a2d6520cf4cf14a11ef95"
},
{
"actor": "635611eb5a71beb6c5bf0b99",
"roleAs": "MJ",
"leadActor": false,
"_id": "636a2d6520cf4cf14a11ef96"
}
],
"poster": {
"url": "https://res.cloudinary.com/debfn35m1/image/upload/v1667902823/tajzr9hpulvzqoytgpxu.jpg",
"public_id": "tajzr9hpulvzqoytgpxu",
"responsive": [
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_640/v1667902823/tajzr9hpulvzqoytgpxu.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_470/v1667902823/tajzr9hpulvzqoytgpxu.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_50/v1667902823/tajzr9hpulvzqoytgpxu.jpg"
]
},
"reviews": {
"ratingAvg": "8.0",
"reviewCount": 2
}
},
This is my desired result:
{
"id": "635611395a71beb6c5bf0b4d",
"title": "Mission: Impossible - Fallout",
"createdAt": "2022-10-24T04:14:54.445Z",
"cast": [
{
"actor": "635350c581d5b60383f0c4be",
"roleAs": "Ethan Hunt",
"leadActor": true,
"_id": "635658c18b9e50facd7f1fd1"
},
{
"actor": "63560bf55a71beb6c5bf0b1f",
"roleAs": "Ilsa Faust",
"leadActor": false,
"_id": "635658c18b9e50facd7f1fd2"
}
],
"poster": {
"url": "https://res.cloudinary.com/debfn35m1/image/upload/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"public_id": "vczxb7lgbonjn8ydsyep",
"responsive": [
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_640/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_50/v1666603204/vczxb7lgbonjn8ydsyep.jpg"
]
},
"reviews": {
"ratingAvg": "5.0",
"reviewCount": 2
}
},
Im trying to write a filter function to get all movie that has Tom Cruise with actorId as a parameter but cannot get the result.
Can someone please help me with this ?
Since your actor id is inside a cast array with key actor you must specify your key while match, check the updated code below
exports.actorAggregation = (actorId) => {
return [
{
$lookup: {
from: "Movie",
localField: "cast",
foreignField: "_id",
as: "actorFilter",
},
},
{ $unwind: "$cast" },
{
$match: {
"cast.actor._id": { $in: [actorId] }, // or "cast.actor": { $in: [actorId] },
status: { $eq: "public" },
},
},
{
$project: {
title: 1,
poster: "$poster.url",
responsivePosters: "$poster.responsive",
createdAt: "$createdAt",
},
},
];
};

Use Mongoose aggregate to fetch object inside of an array

Here is my MongoDB schema:
{
"_id": "603f23ff6c1d862e5ced9e35",
"reviews": [
{
"like": 0,
"dislike": 0,
"_id": "603f23ff6c1d862e5ced9e34",
"userID": "5fd864abb53d452e0cbb5ef0",
"comment": "Not so good",
},
{
"like": 0,
"dislike": 0,
"_id": "603f242a6c1d862e5ced9e36",
"userID": "5fd864abb53d452e0cbb5ef0",
"comment": "Not so good",
}
]
productID:"hdy6nch99dndn"
}
I want to use aggregate to get the review object of a particular id. I tried but not with any success.
Here is my code:
ProductReview.aggregate([
{ $match: { productID: productID } }
])
$match
$unwind
db.collection.aggregate([
{
$match: {
productID: 1
}
},
{
$unwind: "$reviews"
},
{
$match: {
"reviews._id": 2
}
}
])
Output:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"productID": 1,
"reviews": {
"_id": 2,
"comment": "second comment",
"dislikes": [
{
"userID": 3
},
{
"userID": 4
}
],
"likes": [
{
"userID": 1
},
{
"userID": 2
}
]
}
}
]
Mongo Playground: https://mongoplayground.net/p/qfWS1rCuMfc

How to bulk update the array of values in MongoDB?

I have an array of values to update with existing array. I tried with $set it throws a error. If I have an array of values to update it should update matching item in the array.
1.If I have following documents in a collection
table
[
{
"id": 1,
"name": "Fresh Mart",
"products": [
{
"name": "Onion",
"qty": 10,
"price": "85"
},
{
"name": "Tomato",
"qty": 10,
"price": "85"
}
]
},
{
"id": 2,
"name": "Alfred super market",
"products": [
{
"name": "Onion",
"qty": 10,
"price": "85"
},
{
"name": "Tomato",
"qty": 10,
"price": "85"
}
]
}
]
Following query updates one product in first document:
Query
db.collection.update({
"$and": [
{
id: 1
},
{
"products.name": "Onion"
}
]
},
{
"$set": {
"products.name": "Onion Updated"
}
})
I tried to update both products in the first document with following query:
db.collection.update({
"$and": [
{
id: 1
},
{
"products.name": [ "Onion", "Tomato" ]
}
]
},
{
"$set": {
"products.name": "Onion Updated"
}
})
db.collection.update({
id: 1
},
{
"$addToSet": {
"products": {
"$each": [
{
"name": "Onion Updated",
"qty": 10,
"price": "85"
},
{
"name": "Tomato Updated",
"qty": 10,
"price": "85"
}
]
}
}
})
I used $addToSet it will not allow the duplicates. Is possible to replace existing value with $addToSet
but it didn't update the document.
This answer is the dynamic approach of this answer https://stackoverflow.com/a/49870042/8987128
Configure your payload
let id = 1;
let updateName = [
{
oldName: "Onion",
newName: "Onion Updated"
},
{
oldName: "Tomato",
newName: "Tomato Updated"
},
];
Prepare arrayFilters and set conditions
let arrayFilters = [];
let set = {};
updateName.forEach((v, i) => {
arrayFilters.push({ ["p"+i]: v.oldName });
set["products.$[p"+i+"].name"] = v.newName;
});
Update query
db.collection.update(
{ id: id },
{ $set: set },
{ arrayFilters: arrayFilters }
)
Playground

I need to push into nested array in node mongoose

I used node mongoose.
I need to update this array push new item into Breackfast(mealList.foodList.breackfast || any),
I want to add new foodlist by time can you please give me suggestion for how to do,
{
"_id": "5fe43eb44cd6820963c98c32",
"name": "Monday Diet",
"userID": "5f225d7458b48d0fe897662e",
"day": "Monday",
"type": "private",
"mealList": [
{
"_id": "5fe43eb44cd6820963c98c33",
"time": "Breakfast",
"foodList": [
{
"_id": "5fe43eb44cd6820963c98c34",
"foodName": "Eggs",
"Qty": "2",
"calories": "calories",
"category": "category"
}
]
},
{
"_id": "5fe43eb44cd6820963c98c36",
"time": "Lunch",
"foodList": [
{
"_id": "5fe43eb44cd6820963c98c37",
"foodName": "food1",
"Qty": "100g"
},
]
}
],
"createdAt": "2020-12-24T07:09:40.141Z",
"updatedAt": "2020-12-24T07:09:40.141Z",
"__v": 0
}
I tried:
Diet.updateOne(
{ "Diet.mealList._id": req.body.mealId },
// { $push: { "Diet.0.mealList.$.foodList": req.body.foodList } },
{ $push: { foodList: req.body.foodList } }
)
Few Fixes:
convert your string _id to object type using mongoose.Types.ObjectId
remove Diet from first and push object in foodList
Diet.updateOne({
"mealList._id": mongoose.Types.ObjectId(req.body.mealId)
},
{
$push: {
"mealList.$.foodList": req.body.foodList
}
})
Playground

Resources