I've this complex structure in a project I'm working on, and I can't find a way to bulk add some values in the "parametri" array.
Here is an example document:
My goal is to add some values to "parametri" array that is inside the Object at position 1 of the array "protocolli".
In mongoDB Compass I can do a select using "'protocolli.nome': 'protocollo-2'", so I've tried the following code (the project is written in TS, uses a NestJs backend and Mongoose to communicate with MongoDB):
this.model.updateMany(
{ 'protocolli.nome': ProtocolloAlert.PROTOCOLLO_2 },
{
$push: {
'protocolli.parametri': {
$each: [
TipoParametro.FAT_MASS,
TipoParametro.DISTANCE,
TipoParametro.MUSCLE_MASS,
TipoParametro.STEPS,
TipoParametro.CALORIES,
TipoParametro.MINUTES,
],
},
},
},
{ multi: true }
)
I've already tried $push, $addToSet, $set with no positive result..
Using this method, I've the following error:
MongoError: Cannot create field 'parametri' in element {protocolli: [ { nome: "protocollo-1", parametri: [ "temp", "spo2", "hr", "sys" ], descrizione: "Attivazione alert in control room, inserimento nei log degli alert in corso, salvataggio nella scheda alert del paziente" }, { nome: "protocollo-2", parametri: [ "dya", "pulse", "fr", "pef", "fev1", "fvc", "fev1fvc", "etco2", "freqRes", "glucose", "weight", "height", "bmi", "bodyFat", "hba1c", "totCh", "triglycerides", "hdl", "ldl" ], descrizione: "Salvataggio nella scheda alert del paziente" } ]}
at Function.create (C:....\node_modules\mongodb\lib\core\error.js:57:12)
Thanks in advance.
Related
I have a collection with a layout that looks something like this:
student1 = {
"First_Name": "John",
"Last_Name": "Doe",
"Courses": [
{
"Course_Id": 123,
"Course_Name": "Computer Science",
"Has_Chosen_Modules": false
},
{
"Course_Id": 284,
"Course_Name": "Mathematics",
"Has_Chosen_Modules": false
}
]
};
I also have the following update query:
db.Collection_Student.update(
{
$and: [
{First_Name: "John"},
{Last_Name: "Doe"}
]
},
{
$set : { "Courses.0.Has_Chosen_Modules" : true }
}
);
This code will currently update the Computer Science Has_Chosen_Modules value to true since the index is hardcoded. However, what if I wanted to update the value of Has_Chosen_Modules via the Course_Id instead (as the course might not necessarily be at the same index every time)? How would I achieve this without it affecting the other courses that a given student is taking?
You can select any item in the sub array of your document by targeting any property in the sub array of your document by using dot .
You can easily achieve this by the following query.
db.Collection_Student.update(
{
First_Name: "John",
Last_Name: "Doe",
'Courses.Course_Id': 123
},
{
$set : { "Courses.$.Has_Chosen_Modules" : true }
}
);
Conditions in search filter are by default treated as $and operator, so you don't need to specifically write $and for this simple query.
We have a MongoDB instance with a collection of users that is something like this:
{
"Username": "Amin-AMD",
"FriendsList": [
{
"UserId": "5e076f4b19e8cd000162c962",
"NickName": "Amin-Mobile",
"ClanName": null,
"ClanId": null,
"Level": NumberInt(1),
"ActiveCosmeticItems": [
"hair0",
"skin0",
"eye0",
"mouth0",
"daub0",
"acc"
],
"IsOnline": false
},
{
"UserId": "5e08a4a119e8cd000167929e",
"NickName": "saeed",
"ClanName": null,
"ClanId": null,
"Level": NumberInt(7),
"ActiveCosmeticItems": [
"hair5",
"skin2",
"eye2",
"mouth10",
"daub0",
"acc0"
],
"IsOnline": false
}
]
}
As shown above, I have embedded a list of Friends in our User's collection. but for a reason, we need to change this model to reference Friends. So I need to write a query to replace the whole FriendModel with just a UserId.
I have reached to this query but it throws an exception.
db.Users.updateMany({ "FriendsList" : { $ne : [] }}, { $set : { "FriendsList.$" : "FriendsList.$.UserId" }})
In fact, for each friend, I just need the UserId so the new FriendsList will be an array and it should be something like this:
{
"Username": "Amin-AMD",
"FriendsList": [
"5e076f4b19e8cd000162c962",
"5e08a4a119e8cd000167929e"
]
}
MongoDB version: 4.2.1
You have to do it in two steps :
Update existing data in DB :
As you can use aggregation pipeline in updates starting MongoDB version 4.2.
Query to update data :
db.collection.updateMany({ "FriendsList" : { $ne : [] }},[{$set :{FriendsList: '$FriendsList.UserId'}}])
But if your FriendsList.UserId are strings better convert them to ObjectId() as like below :
db.colleciton.updateMany({ "FriendsList" : { $ne : [] }},[{$set :{FriendsList: { $map: { input: '$FriendsList.UserId', in: {$toObjectId: '$$this'}} }}}])
Update existing mongoose model to restrict future writes on DB :
Mongoose Model :
So FriendsList will be an array of ObjectId()'s which will be referred to another new schema via ref field.
FriendsList:[{
type: mongoose.Schema.Types.ObjectId,
ref: "FriendList" /** 'FriendList' will be a mongoose schema refers to a collection */
}]
Ref : mongoose-populate
Try using User model
FriendsList:{
type: mongoose.Schema.Types.ObjectId,
ref: "FriendList"
}
I have following collection with me from MongoDB:
{ "results": [
{
"isExist": true,
"isJourneyEnd": true,
"objectId": "9WtZcxWttk",
"sentTo": [
"JeLRe4yH9R"
],
},
{
"isExist": false,
"isJourneyEnd": true,
"objectId": "9WtZcxWtul",
"sentTo": [
"JeLRe4y9HU"
],
}
]}
In actual, there are many entries in this collection, I've just mentioned two.
If I want to write a query for following statement:
"Print element of array whose isExist is true".
I would like to have some guidance over this, as I am new to MongoDB.
Try this :
db.collection.find({isExist: true});
How do I find an element in Meteor.user() and return other element in that same array in mongodb with meteor. How do I find course_id and get classes_id array?
this is in meteor.user
{
"_id": "RoFFcaAfXBeR2napZ",
"emails": [
{
"address": "tong#gmail.com",
"verified": false
}
],
"classes": [
{
"course_id": "svesvinfdsgrvnekuktndvsk",
"classes_id": ["myclass1", "myclass2"]
},
{
"course_id": "cegtrtcrtvw5cgekrgecec",
"classes_id": ["myclass3", "myclass4"]
},
{
"course_id": "rvxwefdsrvyjvyccrhnkik",
"classes_id": ["myclass5", "myclass6"]
},
],
"courses": [
"qwmZdgQbrZ3rmHdN8"
]
}
You can do it on the server using the Mongo's $ projection operator, but you cannot get the same functionality using MiniMongo out of the box, as it does not support this operator.
Let courseId hold the desired course id.
On the server, using:
c.find({"classes.course_id": courseId},{fields:{"courses.$": 1}})
should yield the desired result.
You will have to refactor your collection or use other tricks in order to get the same result on the client side.
One trick that comes to mind is using a mapping to leave only the desired courses:
function getClasses(courseId){
return myCollection.find({"classes.course_id": courseId}).map((student) => {
student.classes = _.filter(student.classes, (el) => el.course_id === courseId)
return student;
});
}
which also keeps your query reactive.
By default Meteor subscribes only the _id and profile object to the client. so you'll not be able to fetch your class records. you need to make a custom publish which returns your desired records and subscribe to that publication.
The question is quite easy. I have the following document in mongoDb:
_id : ObjectId("519e3c14ade67153e9a003a0")
status:1,
name:"name",
details:
{
crm:115,
webs:
[
{ tag:"blog" , url:"http://..."}
],
contacts:
[
{
_id:ObjectId("009e37e1ade67153e9a0039e"),
name:"me",
phones:
[
{ tag:"home", number:"123..." },
{tag:"mobile", number:"123456789"}
]
}
]
}
I am trying to update one fo the phones in the subdocument details.contacts doing this:
db.new.update(
{
_id : ObjectId("519e3c14ade67153e9a003a0"),
"details.contacts._id": ObjectId("009e37e1ade67153e9a0039e"),
"details.contacts.phones.tag":"home"
},
{
$set:
{
"details.contacts.$.phones.$":
{
tag:"home",
number:"965923777"
}
}
})
and finally I get the following error: Cannot apply the positional operator without a corresponding query field containing an array.
There is anyway to update the document in this way or i should send all the phones to update this field?