Update an array using Jongo - mongodb

I have a mongodb collection of the form
{
"_id":"id",
"userEmail":"userEmailFromCustomerCollection",
"customerFavs":[
"www.xyz.com",
"www.xyz.com",
"www.xyz.com"
]
}
I need to add an element to the customers favs array using Jongo , I am using the following code snippet to do so .
String query = "{userEmail:'"+emailId+"'}";
customerFavCollection.update(query).with("{$addToSet:{customerFavs:#}}", favUrl);
My problem , is that I need to upsert the document if the document does not
exist already , how can I do so using Jongo, I know an easier option would be to retrieve the document by Id and if it does not exist then insert the document using save() , but I am trying to avoid the extra retrieve.

You can add upsert() on the query.
customerFavCollection.update("userEmail:#", emailId)
.with("{$addToSet:{customerFavs:#}}", favUrl)
.upsert();

Related

how to find item in mongo collection when _id is object?

I have mongo collection which have _id key as object of 2 key value pair. (_id = {"id":123, "slice":1}). how can I use pymongo find() to fetch an item using _id? sample collection item looks like this.
Use the uuid module as follows:
db.foo.drop()
import uuid
uu = uuid.uuid4()
uu2 = uuid.uuid4()
db.foo.insert_one({'_id':{'execution_id':uu, 'slice':1}, 'realm':'bar'})
print("should find it:", db.foo.find_one({'_id':{'execution_id':uu, 'slice':1}}))
print("should NOT find it:", db.foo.find_one({'_id':{'execution_id':uu2, 'slice':1}}))

Can we query with _id object on mongodb with mongoClient

I am trying to query on mongodb with _id field
I am doing it like this
1st way:
MongoDatabase mongoDatabase = mongoClient.getDatabase(mongoDatabaseName);
FindIterable<MyEntity> iterable =
mongoDatabase.getCollection(tablename).find(eq("_id",
agentId), MyEntity.class);
iterable.getFirst(); // Thats always null
2nd way:
Document document =
mongoDatabase.getCollection(tableName).find(eq("_id", new
ObjectId(agentId))).first();
with 2nd way , document is there ,but then i am not able to change it to my Entity , I tried with converting from json with jackson , but then it gives error because in my entity there is "id" not "_id" and thats a string , not object.
Can i get some hint please.

MongoDB Morphia Update multi=true VS bulk update

I want to update 10,000 documents in a single web request. I intend to update only one field (which is indexed) in all the documents matched with some criteria with same value.
I see morphia 1.3.2 always set multi=true parameter in update call. Is it enough for updating 10,000 document? Or there are any bulk update functionality in morphia.
The following code should work for you.
Query<Entity> query = datastore.createQuery(Entity.class);
query.filter("name = ", "xxx");
UpdateOperations<Entity> updateOperations = datastore.createUpdateOperations(Entity.class).set
("yyy", 200);
UpdateResults updateResults = datastore.update(query, updateOperations, false, null);
All the documents in the collection with name = 'xxx' will now have all their 'yyy' attribute equal to 200.

update a field with the value of other field

How can I update a field with the value of other field?
For example, I want to update the field updated_at with the value of the field created_at (it's like cloning fields)
$dm->createQueryBuilder('MyBundle:MyService')
->update()
->multiple(true)
->field('updated_at')->set(CREATED_AT_ATRIBUTE)
->getQuery()
->execute();
Thanks
Option #1: Application side update
The easiest approach when using Doctrine ODM is to perform the update on the application side. So you fetch all the objects you want to update, make the necessary adjustments and flush them.
$services = $dm->createQueryBuilder('MyBundle:MyService')
->getQuery()
->execute();
foreach ($services as $service) {
$service->setUpdatedAt($service->getCreatedAt());
}
$db->flush();
$services represents the mongo cursor, which will fetch the documents as you iterate. You can set eagerCursor to true if you want to fetch all the documents from the collection at once.
Option #2: Database side update
You can also perform the update directly on the database itself. To do so however, you'll need to create the query yourself as the query builder doesn't support this functionality.
// Get MongoDB instance from DocumentManager
$mongo = $dm->getDocumentDatabase('Fully/Qualified/Class/Name')
->getMongoDB();
// Iterate over the collection and update each document
$mongo->execute('
db.MyServiceCollection.find().forEach(function (item) {
db.MyServiceCollection.update(
{_id: item._id},
{$set: {updated_at: item.created_at}}
);
});
');
The function used in forEach is just a regular javascript function, so you can insert some more logic in there if you need more control over what you update.

Search for ObjectId of a document: pymongo

I want to access a document in collection by 'name' attribute for getting its ObjectId so that i can insert that unique objectid to other document for reference.
cursorObject = db.collectionIngredient.find({'name': 'sugar'})
I want _id field of cursorObject.
cursorObject.'_id' or cursorObject._id not working.
I have tried __getitem__, __getattribute__ and so much internet surfing but couldn't able to find a way.
Please help
First, as #jjmartinez pointed out, find returns a cursor, which you need to iterate over, in order to get hold of the documents returned by your query. The _id field belongs to the documents, not the cursor.
I'm guessing that in your case the name is unique, so you can avoid cursor/iterating if you use find_one instead of find. Then you get the document directly.
Then, to access the _id, you just need a standard dict-item access:
id = doc['_id']
So we get:
ingredient = db.collectionIngredient.find_one({'name': 'sugar'})
if ingredient is not None:
id = ingredient['_id']
else:
id = None
When you do cursorObject = db.collectionIngredient.find({'name': 'sugar'}) you have a collection of documents, not a single element. So you need to explore all the collection. You need to iterate inside the cursor:
try:
cursorObject = db.collectionIngredient.find({'name': 'sugar'})
except:
print "Unexpected error:", sys.exc_info()[0]
for doc in cursorObject:
print doc
Here you have the Pymongo Tutorial