mongo db query to update document containing map object - mongodb

I have below object in mongodb.
db.agedClientPosition.find().pretty(); {
"_id": ObjectId("596b0f02abc9b006c7de33fb"),
"_class": "org.maruti.mfm.data.entity.AgedClientPosition",
"ageBucket": {
"03-Jul-2017": 3482.896,
"05-Jul-2017": 2403.1168,
"10-Jul-2017": 299.4155
},
"divPayoutBucket": {
},
"createdOn": ISODate("2017-07-16T07:00:18.769Z"),
"modifiedOn": ISODate("2017-07-16T07:01:29.221Z"),
"client": DBRef("client", ObjectId("59544747e6de8f0328c9e8bb")),
"folio": DBRef("folio", ObjectId("5954475fe6de8f0328c9e8bc")),
"scheme": DBRef("scheme", ObjectId("5953c0c0e6de8f024753e3e1"))
}
and for all the ageBucket I want to increment date by 1 day.
Can I achieve this using mondodb query?

Related

Count document satisfies criteria in MongoDB Compass

Below one of the document inside my test.users collection.
{
"_id": {
"$oid": "62ef8c502935226353a97efb"
},
"workspaces": [
{
"$oid": "62ef8c722935227aaca97eff"
}
],
"emailConfirmed": true,
"ipInfo": {
"ip": "191.23.43.218",
"region": "Krasnodarskiy",
"country": "RU",
"timezone": "Europe/Moscow"
},
"__v": 0
}
I want to count the number of country of RU in test.users collection in MongoDB compass, how should I do it? I only saw filter, project, sort, collation under Documents as follows in Mongo DB compass, is there a way I can directly enter a mongoDB query?
You can use the mongosh shell present below, or you can directly check the count below FIND button after running your query, text is like Displaying document x of y:

Update query for Mongo document in Redash

I am trying to look for a query to update a record in Mongo document using Redash. I came up with the following query but it does not work. Can anyone please help? What I know about Redash is that it uses Pymongo.
{
"collection": "Application",
"update": [{
"$match": {
"ID": "2001"
},
"$set": {
"ID": "2020"
}
}]
}
Never used Redash, but in pymongo the construct would be:
db = MongoClient()['mydatabase'] # Set the database connection
db.Application.update_one({"ID": "2001"}, {"$set": {"ID": "2020"}}) # Perform the update

update MongoDB document sub object without replacing

So I have this document in my database like below
{
"_id": {
"$oid": "59a8668f900bea0528b63fdc"
},
"userId": "KingSlizzard",
"credits": 15,
"settings": {
"music": 1,
"sfx": 0
}
}
I have this method for updating just specific fields in a document
function setPlayerDataField(targetUserId, updateObject) {
playerDataCollection.update({
"userId": targetUserId //Looks for a doc with the userId of the player
}, { $set: updateObject }, //Uses the $set Mongo modifier to set value at a path
false, //Create the document if it does not exist (upsert)
true //This query will only affect a single object (multi)
);
}
It works fine if I do a command like
setPlayerDataField("KingSlizzard",{"credits": 20});
It would result in the document like this
{
"_id": {
"$oid": "59a8668f900bea0528b63fdc"
},
"userId": "KingSlizzard",
"credits": 20,
"settings": {
"music": 1,
"sfx": 0
}
}
The value for credits is now 20 yay! This is desired.
However, if I do this command...
setPlayerDataField("KingSlizzard",{"settings": {"music":0}});
It would result in the document like this
{
"_id": {
"$oid": "59a8668f900bea0528b63fdc"
},
"userId": "KingSlizzard",
"credits": 20,
"settings": {
"music": 0
}
}
All I wanted to do was set only the settings/music value to 0. This result is NOT desired since we lost the sfx value.
So my question is, how do I update a value in a sub object without replacing the whole sub object itself?
To set a specific property of a child document, use dot notation. In your example, write it as:
setPlayerDataField("KingSlizzard", {"settings.music": 0});
See the example in the MongoDB docs.
To specify a <field> in an embedded document or in an array, use dot notation.

Cannot add _id field to mongo subdocument in Mlab

In my Mlab mongo 3.2 database I have a collection that looks like this:
{
"_id": {
"$oid": "5752d....87985"
},
"name": "...etation",
"description": null,
"user_id": ".....",
"questions": [
{
"prompt": "The conclusions drawn seemed clear to most researchers, however, others were unconvinced, arguing that everything is open to ____________.",
"answer": "interpretation",
"created_at": "2014-11-09T14:59:38.154",
"updated_at": "2014-11-09T14:59:38.154",
"filled_answer": null
},
{
"id": 922,
"prompt": "His existential quest for Truth is in fact the key to his understanding and ____________ of the Bhagavad-Gītā.",
"answer": "interpretation",
"created_at": "2014-10-03T08:07:40.295",
"updated_at": "2014-10-03T08:07:40.295",
"filled_answer": null
},
}
There are two problems with the questions subdocument that I am struggling with:
Sometimes but not always there is a legacy "id" field that I want to $unset but my query is not working.
I want to add an _id ObjectID field where they do not already exist. Currently some have them and some don't.
I have tried a number of queries but none seem to work. For example:
db.droplets.updateMany({"questions.$._id": { $exists: false }},{ $set: {"questions.$._id": new ObjectId()}},{"multi": true, "upsert": true})
Mongo tells me "The positional operator did not find the match needed from the query"
Update
I have successfully found a way to delete all the questions using the following script:
db.droplets4.find().forEach(function (doc) {
doc.questions.forEach(function (question) {
if (question.id) {
delete question.id
}
});
db.droplets.save(doc);
});
But the same strategy is not working for adding Object IDs. This code does not work:
db.droplets4.find().forEach(function (doc) {
doc.questions.forEach(function (question) {
if (!question._id) { question._id = new ObjectId() }
});
db.droplets.save(doc);
});
This should work fine for you
db.droplets4.updateMany( {
"questions._id" : null
},{ $set: {"questions.$._id": new ObjectId()}},{"multi": true, "upsert": true})

Nested search using MongoDB template

I have below document in Mongo DB and I wrote a java code to get data from innermost element . For some reason its not returning me any results for it.
Input data
{
"_id": "59036b0fa036cc28c8e07db6",
"srcName":"test1",
"sections": [{
"_id": "8769669696",
"data": [{
"srcKey": "Bonds",
"rowIdx": 0,
"values": [{
"srcDesc": "Assets",
"valuesNumber": 10000
},
{
"srcDesc": "NonAssets",
"valuesNumber": 75500
},
{
"srcDesc": "liabilities",
"valuesNumber": 1566
}
]
},
{
"srcKey": "01",
"rowIdx": 1,
"values": [{
"srcDesc": "NonAssets",
"valuesNumber": 1566
}]
}
]
}]
}
The result I want is
select valuesNumber from...where srcName="test1" AND srcKey="Bonds" AND srcDesc="Assets"
Java code is as below
AggregationOperation match=Aggregation.match(Criteria.where("srcName").in("test1")
.and("sections.data.values.srcDesc").in("Assets")
.and("sections.data.srcKey").in("Bonds"));
AggregationOperation unwind1=Aggregation.unwind("sections");
AggregationOperation unwind2=Aggregation.unwind("sections.data");
AggregationOperation unwind3=Aggregation.unwind("sections.data.values");
Aggregation aggregation=Aggregation.newAggregation(match,unwind1,unwind2,unwind3,match);
BasicDBObject basicDBObject=mongoTemplate.aggregate(aggregation,"InsStatData",BasicDBObject.class).getUniqueMappedResult();
It resolved my question. I just had to do a proper mapping to get Mapped results. that was not there in original code. – user3516787 just now edit