Updating document with object field - mongodb

I am new to MongoDB, learning from its documentation but can't find a way to update the document field using MongoDB shell
When I tried to insert the "cancellation" object with either field the query works fine.
db.inventory.update({},
{
$set : { "cancellation":
{
{"date" : new Timestamp()},
{"reason" : "null"}
}
}
},
{upsert : false,multi : true})
It shows
"SyntaxError: invalid property id #(shell)"
on executing this query

Your query is wrong. Try this:
db.inventory.update({},{$set : { "cancellation":
{
"date" : new Timestamp(),
"reason" : "null"
}
} },{upsert : false,multi : true})

Related

MONGODB - cast type of every object in array of objects

I have MongoDB Collection where some documents have arrays of objects. One of the fields of this objects is timestamp.
The problem is that historically some of timestamp values are Strings (e.g. '2018-02-25T13:33:56.675000') or Date and some of them are Double (e.g. 1528108521726.26).
I have to convert all of them to Double.
I've built the query to get all the documents with the problematic type:
db.getCollection('Cases').find({sent_messages: {$elemMatch:{timestamp: {$type:[2, 9]}}}})
And I also know how to convert Date-string to double using JS:
new Date("2018-02-18T06:39:20.797Z").getTime()
> 1518935960797
But I can't build the proper query to perform the update.
Here is an example of such a document:
{
"_id" : ObjectId("6c88f656532aab00050dc023"),
"created_at" : ISODate("2018-05-18T03:43:18.986Z"),
"updated_at" : ISODate("2018-05-18T06:39:20.798Z"),
"sent_messages" : [
{
"timestamp" : ISODate("2018-02-18T06:39:20.797Z"),
"text" : "Hey",
"sender" : "me"
}
],
"status" : 1
}
After the update it should be:
{
"_id" : ObjectId("6c88f656532aab00050dc023"),
"created_at" : ISODate("2018-05-18T03:43:18.986Z"),
"updated_at" : ISODate("2018-05-18T06:39:20.798Z"),
"sent_messages" : [
{
"timestamp" : 1518935960797.00,
"text" : "Hey",
"sender" : "me"
}
],
"status" : 1
}
As per your question, you are trying to fetch the record first.
db.getCollection('Cases').find({sent_messages: {$elemMatch:{timestamp: {$type:[2, 9]}}}})
Then convert date in JS:
new Date("2018-02-18T06:39:20.797Z").getTime()
And then this is an update query:
db.getCollection('Cases').updateOne({_id:ObjectId("6c88f656532aab00050dc023")}, { $set: { "sent_messages.$.timestamp" : "218392712937.0" }})
And if you want to update all records then you should write some forEach mechanism. I think you have already this implemented.
Hope this may help you.
Finally I just do it with JS code that can be run in mongo console:
db.getCollection('Cases').find({sent_messages: {$elemMatch:{timestamp: {$type:[2, 9]}}}}).forEach(function(doc) {
print('=================');
print(JSON.stringify(doc));
doc.sent_messages.forEach(function(msg){
var dbl = new Date(msg.timestamp).getTime();
print(dbl);
msg.timestamp = dbl;
});
print(JSON.stringify(doc))
db.Cases.save(doc);
} )
Thanks all for your help!

mongodb findOneAndUpdate with flatten $set with index position is not inserting as an array

I am writing generic code which will do both add and update as an atomic operation therefore used findOneAndUpdate. My flatten data with array is inserted as object instead of array. Following are details.
db.test.findOneAndUpdate({"saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083"},{$set:{"price.priceTier.0.unitSold": 1,}}, {upsert:true})
db.test.find()
{ "_id" : ObjectId("5b0173fbcd90c934727269ac"), "saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083", "price" : { "priceTier" : { "0" : { "unitSold" : 1 } } } }
How can I make sure that {$set:{"price.priceTier.0.unitSold": 1,}} should add as an array as below?
{ "_id" : ObjectId("5b0173fbcd90c934727269ac"), "saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083", "price" : { "priceTier" : [{ "unitSold" : 1 } ]} }
Since I am trying to write generic code and using flat npm module to flatten my input data to convert into mongodb query therefore I am trying not to change my query if possible.
Please help.
db.test.findOneAndUpdate({"saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083"},{$set:{"price.priceTier":{$push:{"unitSold": 1}}}, {upsert:true})

How to return specific field's value in mongodb

how can I return a specific value for a specific document in MongoDB? For example, I have a schema that looks like:
{
"_id" : "XfCZSje7GjynvMZu7",
"createdAt" : ISODate("2015-03-23T14:52:44.084Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$tcb01VbDMVhH03mbRdKYL.79FPj/fFMP62BDpcvpoTfF3LPgjHJoq"
},
"resume" : {
"loginTokens" : [ ]
}
},
"emails" : {
"address" : "abc123#gmu.edu",
"verified" : true
},
"profile" : {
"companyName" : "comp1",
"flagged" : true,
"phoneNum" : "7778883333"
}}
I want to return and store the value for profile.flagged specifically for the document with _id : XfCZSje7GjynvMZu7. So far I have tried:
db.users.find({_id:'myfi3E4YTf9z6tdgS'},{admin:1})
and
db.users.find({_id: 'myfi3E4YTf9z6tdgS'}, {profile:admin});
I want the query to return true or false depending on the assigned value.
Can someone help? Thanks!
MongoDB queries always return document objects, not single values. So one way to do this is with shell code like:
var flagged =
db.users.findOne({_id: 'myfi3E4YTf9z6tdgS'}, {'profile.flagged': 1}).profile.flagged;
Note the use of findOne instead of find so that you're working with just a single doc instead of the cursor that you get with find.
The correct answer here is the method .distinct() (link here)
Use it like this:
db.users.find({_id:'myfi3E4YTf9z6tdgS'},{admin:1}).distinct('admin')
The result will be: 1 or 0

Mongo database Query

I'm new to mongo database.Please help me in writing the query updation. I already had a collection in mongo and i would like to add a new field in existing object field.the structure is as follows.
{
"_class" : "PersistentContent",
"originalId" : "2070",
"videoInfo" : {
"test1" : ["res"]
},
}
I would like to update the structure to below format.
{
"_class" : "PersistentContent",
"originalId" : "2070",
"videoInfo" : {
"test1" : ["res"],
"test2" : ["res2"]
},
}
How to update the collection and add test2 into videoInfo tag.
use
db.test.update({"originalId" : "2070"},
{
$set : { "videoInfo.test2" : ["res2"] }
})

Query date based using milliseconds time on MongoDB

I need to search all records that match a date condition. On MongoDB I've a bunch of data like this:
{
"_id" : "9ed3b937-0f43-4613-bd58-cb739a8c5bf6",
"userModels" : {
"5080" : {
"generated_date_timestamp" : NumberLong(1413382499442),
"model_id" : 5080,
},
}
"values" : {}
}
I'm not able to convert that NumberLong in something that can be used by this query:
db.anonProfile.find({
"userModels.5080.generated_date_timestamp" : { "$gte" : ISODate("2013-10-01T00:00:00.000Z") }
});
"_id" has been saved as String so I cannot use for a ObjectID search. [btw, is it possible to do?]
Any clue?
Tnx, Andrea
You can query by
db.anonProfile.find({
"userModels.5080.generated_date_timestamp" : { "$gte" : ISODate("2013-10-01T00:00:00.000Z").getTime() }
});