How can I add array data to the object if field exist/not exist in mongo db - mongodb

This is my expected result:
"ForgotPassword": [
{
"UpdatedOn": ISODate("2017-12-06T11:23:23.0Z"),
},
{
"UpdatedOn": ISODate("2017-12-06T11:45:13.0Z"),
}
]
And this what I am getting:
"ForgotPassword": {
"UpdatedOn": [
ISODate("2017-12-20T11:48:15.0Z"),
ISODate("2017-12-20T11:48:30.0Z"),
ISODate("2017-12-21T11:57:21.0Z")
]
}
Actually Forgot password field will not present in the collection document.
When I add the first time it should create Forgotpassword field and inside updatedon should store
And
when I add the second time the inside the Forgotpassword, updatedon should repeat for me it is storing inside updateon
This is my query:
$updateQuery = $queryUpdate->update(
array("CollaboratorId"=>(int)$collaboratorId), //query condition
array('$addToSet'=>array('ForgotPassword.UpdatedOn'=>$currentDate)),
array('upsert'=>1)
);

$queryUpdate->findAndModify(
array("CollaboratorId"=> (int)$collaboratorId),
array('$addToSet'=> array('ForgotPassword' =>array("UpdatedOn" => $currentDate))),
array('new' => 1,"upsert"=>1)
);
With upsert and new and findandmodify and addtoset it is working

Related

How can I return the element I'm looking for inside a nested array?

I have a database like this:
[
{
"universe":"comics",
"saga":[
{
"name":"x-men",
"characters":[
{
"character":"wolverine",
"picture":"618035022351.png"
},
{
"character":"cyclops",
"picture":"618035022352.png"
}
]
}
]
},
{
"universe":"dc",
"saga":[
{
"name":"spiderman",
"characters":[
{
"character":"venom",
"picture":"618035022353.png"
}
]
}
]
}
]
and with this code I manage to update one of the objects in my array. specifically the object where character: wolverine
db.mydb.findOneAndUpdate({
"universe": "comics",
"saga.name": "x-men",
"saga.characters.character": "wolverine"
}, {
$set: {
"saga.$[].characters.$[].character": "lobezno",
"saga.$[].characters.$[].picture": "618035022354.png",
}
}, {
new: false
}
)
it returns all my document, I need ONLY the document matched
I would like to return the object that I have updated without having to make more queries to the database.
Note
I have been told that my code does not work well as it should, apparently my query to update this bad, I would like to know how to fix it and get the object that matches these search criteria.
In other words how can I get this output:
{
"character":"wolverine",
"picture":"618035022351.png"
}
in a single query using filters
{
"universe": "comics",
"saga.name": "x-men",
"saga.characters.character": "wolverine"
}
My MongoDB knowledge prevents me from correcting this.
Use the shell method findAndModify to suit your needs.
But you cannot use the positional character $ more than once while projecting in MongoDb, so you may have to keep track of it yourself at client-side.
Use arrayFilters to update deeply nested sub-document, instead of positional all operator $[].
Below is a working query -
var query = {
universe: 'comics'
};
var update = {
$set: {
'saga.$[outer].characters.$[inner].character': 'lobezno',
'saga.$[outer].characters.$[inner].picture': '618035022354.png',
}
};
var fields = {
'saga.characters': 1
};
var updateFilter = {
arrayFilters: [
{
'outer.name': 'x-men'
},
{
'inner.character': 'wolverine'
}
]
};
db.collection.findAndModify({
query,
update,
fields,
arrayFilters: updateFilter.arrayFilters
new: true
});
If I understand your question correctly, your updating is working as expected and your issue is that it returns the whole document and you don't want to query the database to just to return these two fields.
Why don't you just extract the fields from the document returned from your update? You are not going to the database when doing that.
var extractElementFromResult = null;
if(result != null) {
extractElementFromResult = result.saga
.filter(item => item.name == "x-men")[0]
.characters
.filter(item => item.character == "wolverine")[0];
}

MongoDB updating the wrong subdocument in array

I've recently started using MongoDB using Mongoose (from NodeJS), but now I got stuck updating a subdocument in an array.
Let me show you...
I've set up my Restaurant in MongoDB like so:
_id: ObjectId("5edaaed8d8609c2c47fd6582")
name: "Some name"
tables: Array
0: Object
id: ObjectId("5ee277bab0df345e54614b60")
status: "AVAILABLE"
1: Object
id: ObjectId("5ee277bab0df345e54614b61")
status: "AVAILABLE"
As you can see a restaurant can have multiple tables, obviously.
Now I would like to update the status of a table for which I know the _id. I also know the _id of the restaurant that has the table.
But....I only want to update the status if we have the corresponding tableId and this table has the status 'AVAILABLE'.
My update statement:
const result = await Restaurant.updateOne(
{
_id: ObjectId("5edaaed8d8609c2c47fd6582"),
'tables._id': ObjectId("5ee277bab0df345e54614b61"),
'tables.status': 'AVAILABLE'
},
{ $set: { 'tables.$.status': 'CONFIRMED' } }
);
Guess what happens when I run the update-statement above?
It strangely updates the FIRST table (with the wrong table._id)!
However, when I remove the 'tables.status' filter from the query, it does update the right table:
const result = await Restaurant.updateOne(
{
_id: ObjectId("5edaaed8d8609c2c47fd6582"),
'tables._id': ObjectId("5ee277bab0df345e54614b61")
},
{ $set: { 'tables.$.status': 'CONFIRMED' } }
);
Problem here is that I need the status to be 'AVAILABLE', or else it should not update!
Can anybody point me in the wright direction with this?
according to the docs, the positional $ operator acts as a placeholder for the first element that matches the query document
so you are updating only the first array element in the document that matches your query
you should use the filtered positional operator $[identifier]
so your query will be something like that
const result = await Restaurant.updateOne(
{
_id: ObjectId("5edaaed8d8609c2c47fd6582"),
'tables._id': ObjectId("5ee277bab0df345e54614b61"),
'tables.status': 'AVAILABLE'
},
{
$set: { 'tables.$[table].status': 'CONFIRMED' } // update part
},
{
arrayFilters: [{ "table._id": ObjectId("5ee277bab0df345e54614b61"), 'table.status': 'AVAILABLE' }] // options part
}
);
by this way, you're updating the table element that has that tableId and status
hope it helps

Meteor/Mongo - add/update element in sub array dynamically

So I have found quite few related posts on SO on how to update a field in a sub array, such as this one here
What I want to achieve is basically the same thing, but updating a field in a subarray dynamically, instead of just calling the field name in the query.
Now I also found how to do that straight in the main object, but cant seem to do it in the sub array.
Code to insert dynamically in sub-object:
_.each(data.data, function(val, key) {
var obj = {};
obj['general.'+key] = val;
insert = 0 || (Documents.update(
{ _id: data._id },
{ $set: obj}
));
});
Here is the tree of what I am trying to do:
Documents: {
_id: '123123'
...
smallRoom:
[
_id: '456456'
name: 'name1'
description: 'description1'
],
[
...
]
}
Here is my code:
// insert a new object in smallRoom, with only the _id so far
var newID = new Mongo.ObjectID;
var createId = {_id: newID._str};
Documents.update({_id: data._id},{$push:{smallRooms: createId}})
And the part to insert the other fields:
_.each(data.data, function(val, key) {
var obj = {};
obj['simpleRoom.$'+key] = val;
console.log(Documents.update(
{
_id: data._id, <<== the document id that I want to update
smallRoom: {
$elemMatch:{
_id : newID._str, <<== the smallRoom id that I want to update
}
}
},
{
$set: obj
}
));
});
Ok, having said that, I understand I can insert the whole object straight away, not having to push every single field.
But I guess this question is more like, how does it work if smallRoom had 50 fields, and I want to update 3 random fields ? (So I would NEED to use the _each loop as I wouldnt know in advance which field to update, and would not want to replace the whole object)
I'm not sure I 100% understand your question, but I think the answer to what you are asking is to use the $ symbol.
Example:
Documents.update(
{
_id: data._id, smallRoom._id: newID._str
},
{
$set: { smallroom.$.name: 'new name' }
}
);
You are finding the document that matches the _id: data._id, then finding the object in the array smallRoom that has an _id equal to newId._str. Then you are using the $ sign to tell Mongo to update that object's name key.
Hope that helps

Mongodb: assert that all elements in an array have a field not null

Given a collection with documents like this:
Task Collection document
[
{
"_id"=>BSON::ObjectId('54d674b64d42504b6a000000'),
"submissions"=>
[{"_id"=>BSON::ObjectId('54d674b64d42504b6a010000'),
"grade"=>nil,
"user_id"=>BSON::ObjectId('54d1e2454d42503069060000')},
{"_id"=>BSON::ObjectId('54d674b64d42504b6a020000'),
"grade"=>nil,
"user_id"=>BSON::ObjectId('54d1e2454d42503069070000')},
{"_id"=>BSON::ObjectId('54d674b64d42504b6a030000'),
"grade"=>nil,
"user_id"=>BSON::ObjectId('54d1e2454d42503069080000')}
],
},
{
"_id"=>BSON::ObjectId('54d674b64d42504b6a100000'),
"submissions"=>
[{"_id"=>BSON::ObjectId('54d674b64d42504b6a010000'),
"grade"=>5,
"user_id"=>BSON::ObjectId('54d1e2454d42503069060000')},
{"_id"=>BSON::ObjectId('54d674b64d42504b6a020000'),
"grade"=>7,
"user_id"=>BSON::ObjectId('54d1e2454d42503069070000')},
{"_id"=>BSON::ObjectId('54d674b64d42504b6a030000'),
"grade"=>nil,
"user_id"=>BSON::ObjectId('54d1e2454d42503069080000')}
],
},
{
"_id"=>BSON::ObjectId('54d674b64d42509b6a000000'),
"submissions"=>
[{"_id"=>BSON::ObjectId('54d674b64d42504b6a010000'),
"grade"=>8,
"user_id"=>BSON::ObjectId('54d1e2454d42503069060000')},
{"_id"=>BSON::ObjectId('54d674b64d42504b6a020000'),
"grade"=>7,
"user_id"=>BSON::ObjectId('54d1e2454d42503069070000')},
{"_id"=>BSON::ObjectId('54d674b64d42504b6a030000'),
"grade"=>6,
"user_id"=>BSON::ObjectId('54d1e2454d42503069080000')}
],
}
]
How can I get all the tasks documents whose submissions array contains no nil grade?
The result in the example would contain just the last one.
I am using Mongoid, but I welcome a pure Mongodb query too.
Using elem_match and a negative comparison:
Task.where(:submissions.elem_match => { :grade.ne => nil })

How to make the time stamp difference for inserting and updating record in mongo?

I need to create a time stamp in my mongodb collection. Am using C# in front end .My code is :
internal static void CreateStudent(string Id, string Name,string strUserId)
{
MongoServer server = MongoServer.Create(ConnectionString);
MongoDatabase mydb = server.GetDatabase("Database");
MongoCollection<BsonDocument> Student = mydb.GetCollection<BsonDocument>("Student");
BsonDocument colectionGenre = new BsonDocument {
{ "Code", Id }, //Id is Auto Generated in sql. Fetch from there using Output parameter and save it in one variable and pass that here
{ "Name", Name },
{ "Status","Y"},
{"stamps" , new BsonDocument {
{"Ins_date", DateTime.Now},
{"up_date",""},
{"createUsr", strUserId},
{"updUsr", ""},
{"Ins_Ip", GetIP()},
{"Upd_IP",""}}}
};
Student.Insert(colectionGenre);
}
internal static void UpdateStudent(string Id, string Name,string strUserId)
{
MongoServer server = MongoServer.Create(ConnectionString);
MongoDatabase mydb = server.GetDatabase("Database");
MongoCollection<BsonDocument>Student = mydb.GetCollection<BsonDocument>("Student"); ;
// Query for fetch the ID which is edited by the User...(user can only able to edit the NAME field alone)
var query = new QueryDocument {
{ "Code", Id }};
// After Fetch the correspondent ID it updates the name with the Edited one
var update = new UpdateDocument {
{ "$set", new BsonDocument("Name", Name) }
};
// Updated Query.(Id is same as previous. Name is updated with new one)
{"stamps" , new BsonDocument {
{"up_date",DateTime.Now},
{"updUsr", strUserId},
{"Upd_IP",GetIp()}}}
}}
};
Student.Update(query,update,UpdateFlags.Upsert, SafeMode.True);
}
It works fine for INSERT method with time(Stamp) once the record is created. But the problem is with update method. When user update something the insert time also changed with the updated time..
After User Updates the Name, i want my will collection looks like this
{
"_id" : ObjectId("5178aea4e6d8e401e8e51dc0"),
"Code": 12,
"Name": Sname,
"Stamps:"{
"Ins_date":03:34:00,
"up_date": 04:35:12
}
}
But my problem is both the time will same after update. That is because it takes the current date and time function..How can i achieve the above output.It needs any driver.Suggest something for me...
You're passing in a value for the Ins_date field when you're updating the document. Just remove that from the update document and it won't change it.
var update = new UpdateDocument {
{"$set", new BsonDocument {
{"State_strName", name},
{"stamps" , new BsonDocument {
{"up_date",DateTime.Now},
{"createUsr", ""},
{"updUsr", ""},
{"Ins_Ip", GetIP()},
{"Upd_IP",GetIP()}}}
};
tblmytbl.Update(query, update);
How you are updating the value in the existing document by using unique id or other unique value.Check whether the unique id or value is already exist in your database documents.If it is exist means change the update time only don't do anything..
While updating the data in mongoDB,you are passing the same values for Ins_date and up_date i.e. DateTime.Now(current system date and time).So the same values are updating in your monoDB document.
For this you can do one thing :-
Before updating your mongoDB document you take Ins_date values from your database by using sql query in C#.net and then use this value for Ins_date and for up_date use DateTime.Now then your both values will be different.
var update = new UpdateDocument {
{"$set", new BsonDocument {
{"State_strName", name},
{"stamps" , new BsonDocument {
{"Ins_date", **Ins_date values_from your database**} ,
{"up_date",DateTime.Now},
{"createUsr", ""},
{"updUsr", ""},
{"Ins_Ip", GetIP()},
{"Upd_IP",GetIP()}}}
};
tblmytbl.Update(query, update);
Sounds like what you need is the new $setOnInsert operator which was added in 2.4 for exactly this use case.
When the update with upsert flag results in an insert, you want to $set insert_date to Date.now but when it's a regular update, you don't want to set it at all. So now with your update you should use $set for regular fields you want to set whether it's an update or an insert, but use $setOnInsert for fields that should only be set during insert.
Finally I got answer...In INSERT method Simply pass the below things
{"Insert-stamps" , new BsonDocument {
{"Ins_date", DateTime.Now},
{"createUsr", strUserId},
{"Ins_Ip", GetIP()}}},
{"Update-stamps" , new BsonDocument {
{"up_date",""},
{"updUsr", ""},
{"Upd_IP",""}}}
And In UPDATE method
{"Update-stamps" , new BsonDocument {
{"up_date", DateTime.Now},
{"updUsr", StrUserId},
{"Upd_IP",GetIP()}}}
It works Fine for my standard....