Reputation: 302
{
"_id": "W4ZZxraDXGj3FtJek",
"name": "Rust",
"description": "new programming language by google",
"organization": "rYefzmKDCoqKJQmeA",
"status": "active",
"dateAdded": "2018-02-07T13:51:31.564Z",
"members": [
{
"id": "6BuSTu6GZybkmozWW",
"role": "manager",
"hours": "",
"dateAdded": "2018-02-07T15:13:30.654Z",
"reports": [
{
"date": "2018-02-06T12:39:32.118Z",
"hours": "19123"
},
{
"date": "2018-02-05T12:39:32.118Z",
"hours": "19123"
}
]
},
{
"id": "aFJlejSTu6erawlkjeru",
"role": "manager",
"hours": "",
"dateAdded": "2018-02-07T15:13:30.654Z",
"reports": [
{
"date": "2018-02-06T12:39:32.118Z",
"hours": "19123"
}
}
]
}
]
}
I have a collection like this. What I want to do is search a project by ID, search a single member and find a specific report based on date property. If it is found, I want to update the hours. If it’s not, I want to create a new report object.
I’m creating a test app to learn meteor. Currently new to meteor and NoSQLs (mongoDB)
Projects.update({
_id: projId,
"members.id": memberId
}, {
$set: { "members.$.hours": hours }
});
What I've done so far is update the 'hours' field but I added a new 'reports' field that has a nested objects.
Upvotes: 0
Views: 832
Reputation: 1853
You can go simple route.. Use findOne to get record.
const p = Projects.findOne({_id:id});
//If record exists update or insert.
if(p){
Projects.update({_id:id},{$set:{abcd:defg}});
}else{
Projects.insert({abcd:defg});
}
Have control at each step. findOne query is very efficient.
Upvotes: 1
Reputation: 14436
MongoDB has a concept of upsert and is set within the options within the update function:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
You'll most likely find the $setOnInsert
operator for your case, as by default it only sets the update values that you've specified, if you want to insert other items on the insert but not the update you can use this operator. More information can be found here -https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/
See more reading - https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-option
Upvotes: 2