mongodb embedded document search - mongodb

I have a mongodb collection like as follows . My job is to increase the "rate" of a particular document inside "ratings" key. I can do it by following command in mongo shell. db.amitava1.update({_id:1},{"$inc":{"ratings.0.rating":1 } } ) . . Here by 0 I access the first document in "ratings". But I need to use a variable in place of 0. The following does not work.
x = 0;
db.amitava1.update({_id:1},{"$inc":{"ratings.x.rating":1 } } );
Any help would be greatly appreciated. Thanks,

Try to do it with Template String, to parse x in the ratings.x.rating.
> var x = 0;
> var str = `ratings.${x}.rating`;
> db.amitava1.update({_id:1}, {$inc: {[str]: 1}})

Related

MongoDB console: Getting the _id of a cursor object

Is it possible to get the _id of a cursor? The following method does not work for me.
> var cursor = db.genre.find({name:"romance"})
> db.genre.find({name:"romance"}, {"_id":1})
{ "_id" : ObjectId("5c03537d7d0db45bee0f64d0") } // output
I just would like the value: ObjectId("5c03537d7d0db45bee0f64d0" to be returned.
Thanks to mickl, the answer is
db.genre.find({name:"romance"}, {"_id":1})[0]._id

How to iterate queries in mongo shell

Surely, this is simple. I cannot figure this out. In Mongo shell I have the following command:
db.getCollection("CollectionName")
.findAndModify({query: {"Property.0.Element": {"$type" : 1}},
update: {$set: {"Property.0.Element":""}}
})
If I run this command several times, eventually it returns null and I know that I have changed all of the fields that I wanted to change. If however I run:
for(j = 0; j < 50;j++) {
var loc = "Property."+j+".Element";
db.getCollection("ShelbyCoAssessorDeepStaging")
.findAndModify({query: {loc : {"$type" : 1}},
update: {$set: {loc:""}}
})
}
Then I have null returned, but none of the values actually changed. Why is this? Note: I am running this in studio3T's intellishell against an atlas cluster at version 3.6.6.
You are trying to use dynamic keys for a query object. But JavaScript does not support this approach in object literals. Please consider the following example on the MongoDB shell or Studio 3T's IntelliShell:
> var fieldName = "foo"
> var query = { fieldName: 1 }
> printjsononeline(query)
{ "fieldName" : 1 }
In this small example, we create a variable that contains the name of the key that we want to set inside a query object. But JavaScript does not expect a variable as a key inside an object literal. The symbol is directly used as key name, it absolutely does not matter if the key is quoted or not.
If you want to have dynamic key names in JavaScript, you can use the simple bracket notation (or "member index access"):
> var fieldName = "foo"
> var query = {}
> query[fieldName] = 1
1
> printjsononeline(query)
{ "foo" : 1 }
If we apply this to your example, we get the following code to be run on the MongoDB shell or Studio 3T IntelliShell:
for(j = 0; j < 50;j++) {
var loc = "Property."+j+".Element";
var theQuery = {};
theQuery[loc] = {"$type" : 1};
var theUpdate = {$set: {}};
theUpdate["$set"][loc] = "";
db.getCollection("ShelbyCoAssessorDeepStaging")
.findAndModify({query: theQuery,
update: theUpdate
})
}

MongoDB insert data after find query

I'm using MongoDB with Mongochef GUI over an Ubuntu Virtual Machine. I need to do a Query which insert the data that I have found previously.
How can i do this? I thought something like this:
db.createCollection("prueba", { capped : true, size : 5242880, max : 5000 } )
db.gmap.find( { emotion: 1 } )
db.prueba.insertMany(db.gmap.find( { emotion: 1 } ))
GMAP is other collection that i have and the find query returns needed data.
Thanks
To solve that we need to store result as an array and then insert - please find snippet below:
var a = db.sourceCollection.find().toArray()
db.destinatioCollection.insert(a)
To exclude some fields use the find projection option: in this example the "_id" field is excluded, usefull to insert in the same collection.
To insert many documents use insertMany method:
db.dstColl.insertMany( db.srcColl.find({}, {"_id": false}).toArray() )

use variable to reference a document in mongodb

Here is my statement in mongodb:
var target = db.test.find({},{_id:1}).sort({_id:-1}).limit(1);
which can give me the largest _id. When I type target in shell, the output is like this:
> target
{ "_id" : ObjectId("51e062189c6ae665454e301d") }
However, when I type target again, nothing returns. Also, when I use target in other queries, those queries don't work either. Can anyone help me out?
This is most probably because target becomes a cursor since it is a result of .find(). However you can still obtain the resulting document by using toArray() method of MongoDB cursor like the following:
> var target = db.test.find({},{_id:1}).sort({_id:-1}).limit(1).toArray()
> if (target.length > 0) { target = target[0]; } else { target = null; }
You may find some information on toArray here.

get count of document in Mongodb

My object is like following.
{ "_id" : ObjectId("4ec3ba6fb8af0adbaf2ffc2a"), "list" : { "list1" : "sample", "list2" : "test2" } }
I want to count total record under "list". Can I do this in shell ?
I don't think there are any queries on the database side for that. You could use simple map/reduce but in your case probably the easiest way is to just fetch the whole document and then count the items with javascript loop like this:
document = db.yourcoll.findOne(...);
var count = 0;
for (e in document.list) { ++count; }
You can only do this through either creating a count field on insert of the item, or via code once you have the item echo'd out. You can't count on list once it's in your document.