Mongo Db query inside array of object and update - mongodb

Ok my schema structure is:
"labTest" : [
{
"_id" : ObjectId("56eaab35b5f57f2c1b022b00"),
"test" : "Blood Test"
},
{
"_id" : ObjectId("56eaab35b5f57f2c1b022aff"),
"test" : "Urine Test"
},
{
"_id" : ObjectId("56eaab35b5f57f2c1b022afe"),
"test" : "ECG"
}
],
Now I have the id and test field to this schema, I just want to query and add a status field inside this schema and make it 1.
Any help will be very appreciated

You can do this using commandline very easily. I am considering that your environment is all set. simply type following command in your commandline interface.
db.yourschemaname.update({},{$set:{"status":1}},{multi:true});

Related

Add a new field in Mongo object and initialize with the value from another field, in one query

I want to add a new field to all the mongo objects in one of my collections using one mongo query. This new field will be initialized to the value of another field in its object.
Say the Mongo object is like:
{
"_id" : "24a1aefe-7242-4104-b6a9-8f9993b22019",
"attributes" : {
"product name" : "Duracell Aa Batteries 2 Pc"
},
"sku_id" : "4_5",
"state" : "ENABLED"
}
I want to make all the mongo objects like:
{
"_id" : "24a1aefe-7242-4104-b6a9-8f9993b22019",
"attributes" : {
"product name" : "Duracell Aa Batteries 2 Pc"
},
"sku_id" : "4_5",
"new_sku_id": "4_5"
"state" : "ENABLED"
}
I was able to do this using pymongo, but that requires multiple update queries to be fired to the mongo server and works in a for loop.
Is there a single mongo query that can solve my problem? Please help.
I am using the following mongo query which is not working:
db.skus.update({},{"$set":{"new_sku_id":"$sku_id"}},{multi:true})
But this is not working. It is resulting in the following mongo object:
{
"_id" : "24a1aefe-7242-4104-b6a9-8f9993b22019",
"attributes" : {
"product name" : "Duracell Aa Batteries 2 Pc"
},
"sku_id" : "4_5",
"new_sku_id": "$sku_id"
"state" : "ENABLED"
}
Please help
You cannot refer to other fields in update statement but you can use $addFields to generate that field and $out to rewrite existing collection with the output of aggregation:
db.collection.aggregate([
{
$addFields: {
new_sku_id: "$sku_id"
}
},
{ $out: "collection" }
])
In mongo collection you can run this. This will take time depend on the number documents in the collection.
db.getCollection('skus').find({}).forEach(function(obj){
db.getCollection('skus').update({_id:obj._id},{$set:{new_sku_id: obj.sku_id}})
})

Access document directly by ID

I'm used to working with firebase where I can access a document directly by fetching data from the db like so.
db.collection('collectionName/documentID').get();
I can't seem to find any documentation regarding doing something similar in mongodb. Do I have to use a find query to grab data from a mongodb or have I missed something? Thanks
I'm thinking
const collection = db.collection('collectionName');
collection.findOne({_id: ObjectId('documentID'); });
Since mongo consolse is an interactive javascript shell, One way would be to create a method similar to this:
function collectionNameGet(idToFind) {
return db.collection.find({_id: idToFind });
}
In the mongo shell you can directly get it as below:
db.st4.find({"_id" : "1234"})
Result set:
{ "_id" : "1234", "raw" : { "meas" : { "meas1" : { "data" : "blabla" }, "mesa2" : { "data" : "foo" } } } }
Or by default mongo id as:
db.st1.find({"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4")})
{ "_id" : ObjectId("5c578d57ce9ba4a066ca2fa4"), "name" : "Just a name", "users" : [ "user1", "user2" ] }
For display the result in pretty format
db.st1.find({"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4")}).pretty()
Result set:
{
"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4"),
"name" : "Just a name",
"users" : [
"user1",
"user2"
]
}
Here st4 is my collection name in the database test, so once you are on mongo shell do the below steps before above query:
use test
db.st1.insert({"name" : "Just a name", "users" : [ "user1", "user2" ] })
and then you can query by default _id generated mongo, you can simply make a query to get the recently added documents in the collection st1 as below:
db.st1.find().sort({_id:-1}).limit(1)
Hope this will help you out to do some basic query on mongo shell

Mongo db query where condition for a column (list of values) having a value

I am trying to find a way to filter the records in Mongo db using Spring query.
Here is the scenario, let's see I have an Activity entity/document. One of the fields is a list of names. I want to see if I can get all the records that the names field includes get given value, let's say "Joker".
For example, my json in Mongo is
Activity 1 -
{
"_id" : ObjectId("52c14eb92f7ceb854e445354"),
...
"names" : [{
"username" : "username1",
"realname" : "Super Man"
}, {
"username" : "username2",
"realname" : "Iron Man"
}]
}
Activity 2 -
{
"_id" : ObjectId("52c14eb92f7ceb854e445355"),
...
"names" : [{
"username" : "username3",
"realname" : "Bat Man"
}, {
"username" : "username4",
"realname" : "Joker"
}]
}
And I expect the query will let me get Activity 2 only.
Also, if possible, I prefer to use spring Mongo query in my code. Thanks in advance.
Try
db.collection.find({"names.realname": "Joker"});
I never used Spring query but should be something like
Query query = new Query();
query.addCriteria(Criteria.where("names.realname").is("Joker"));
List<MyClass> users = mongoTemplate.find(query, MyClass.class);

mongo - how to query a nested json

I am a complete mongo newbie. I am using mongo hub for mac. I need to query the for following json -
{ "_id" : ObjectId( "abcd" ),
"className" : "com.myUser",
"reg" : 12345,
"test" : [
{ "className" : "com.abc",
"testid" : "pqrs" } ] }
and find records where testid is pqrs. How would I go about doing that?
You can type {'test.testid': 'pqrs'} in the query field of Mongo Hub.
Looks like test is an array. If you are expecting multiple values in array you can do -
"test": {
"$elemMatch": {
"testid": "pqrs",
}
}

MongoDB $addToSet creates value as object

On an Update, I'm trying to create a new array element or add to an existing array, which is how I interpreted $addToSet to work:
http://www.mongodb.org/display/DOCS/Updating
But what I get if "tag" doesn't exist is the value as an object, not an array:
"tag": {
"0": "FreeShipping"
},
using
db.collection.update({ size : 10.5 }, {$addToSet : {tag : "FreeShipping"}} );
I just tried duplicating this and got the correct result please check below:
> use test
switched to db test
> db.test.insert({item:"test"});
> db.test.findOne();
{ "_id" : ObjectId("4ed69f9d1812423106a229ac"), "item" : "test" }
> db.test.update({item:"test"},{$addToSet:{tag:"FreeShipping"}});
> db.test.findOne();
{
"_id" : ObjectId("4ed69f9d1812423106a229ac"),
"item" : "test",
"tag" : [
"FreeShipping"
]
}
Can you please show your queries for adding it? Along with what version of MongoDB you're currently using as it seems to be working as expected (and as you're assuming).
Thanks!