Update a Mongodb document and add fields - mongodb

I'm trying to update a mongodb document and add some fields but in vain
my initial document looks like this
{"_id" : ObjectId("52c720e3211b6f0a258b4567"),
"email" : "someemail#msn.com",
"date" : ISODate("2014-01-03T20:43:15Z"),
"number" : 0, "accessToken" : "CAAIc2knVS3oBAAWRw5iqTK6mo6BEjwJJtT8PRZBUfhLayyelcXDZBO0pTWULGNPOZAxb9ZAwWk1oQghdcqxRr5yycMvkSokU7vYn3OWQJVWFuxbHC6L6F3NvLAYCrkoPvnoZAmNZBkkvG4qXFQT46hyPrDSc7GTZA1IpxVrQHEGbrwZDZD" }
After Update, I want to add 2 fields to the document which are : username and password.
I've looked into documentation but it doesn't seem to treat this matter.
Thanks a lot

If you're working with a doctrine ODM Document object :
$document->setUsername($username); // $document is your document instance
$document->setPassword($password);
$dm->flush($document); // $dm : document manager
If you want a standalone query (through QueryBuilder) :
$dm->createQueryBuilder('YourBundle:YourDocumentClass')
->field('_id')->Equals("52c720e3211b6f0a258b4567")
->update()
->field('username')->set($username)
->field('password')->set($password)
->getQuery()->execute();
More info and querybuilder examples here :
http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/query-builder-api.html

In the mongo shell you could do it like this:
db.myusers.update(
{_id: ObjectId("52c720e3211b6f0a258b4567")}, // identify document
{$set: {username: 'scott', password: 'tiger'} })
This leaves the other fields untouched.

Related

pymongo update creates a new record without upserting

I have an issue where I do an update on a document, however, the update creates a new document and I'm not upserting in my update.
This is my testing code.
I do a find to see if the document exists by checking if "lastseen" doesn't exist:
result = DATA_Collection.find({"sessionID":"12345","lastseen":{"$exists":False}})
if result.count() == 1:
DATA_Collection.update({"sessionID":"12345"},{"$set":{"lastseen":"2021-05-07"}})
When I do an aggregate check to find duplicates I get a few, one example below.
> db.DATA_Collection.find({ "sessionID" : "237a5fb8" })
{ "_id" : ObjectId("60bdf7b05c961b4d27d33bde"), "sessionID" : "237a5fb8", "firstseen" : ISODate("1970-01-19T20:51:09Z"), "lastseen" : ISODate("2021-06-07T12:34:20Z") }
{ "_id" : ObjectId("60bdf7fa7d35ea0f046a2514"), "sessionID" : "237a5fb8", "firstseen" : ISODate("1970-01-19T20:51:09Z") }
I remove all the records in the collection and rerun the script, the same happens again.
Any advice will be much appreciated.
Firstly your pymongo commands are deprecated; use update_one() or update_many() instead of update(); count_documents() instead of count().
Secondly double check you are referencing the same collections as you mention DATA_Collection and VPN_DATA;
How are you defining a "duplicate"? Unless you create a unique index on the field(s), the records won't be duplicates as they have different _id fields.
You need something like:
record = db.VPN_DATA.find_one({'sessionID': '12345', 'lastseen': {'$exists': False}})
if record is not None:
db.VPN_DATA.update_one({'_id': record.get('_id')}, {'$set': {'lastseen': '2021-05-07'}})

Camel 3.5 MongoDB component and findById with a simple String _id field

I'm using Camel 3.5.
https://camel.apache.org/components/latest/mongodb-component.html#_query_operations
I'm trying retrieve one document from a MongoDb collection but the _id field is an UUID String and i cannot convert it to an ObjectId.
Here is an sample document :
{
"_id" : "7cc141cd-9353-41ab-bc55-a9ab6ffe83ea",
"street" : "2 rue Etienne Marcel",
}
from("direct:findById")
.to("mongodb:myDb?database=flights&collection=tickets&operation=findById")
.to("mock:resultFindById");
Tried this and it works, thx to #LucaBurgazzoli
exchange.getMessage().setBody(document.getString("_id"));

MongoDB Compound text search

I have a collection like this in my mongo database, let's say it's called taxonomic.
{
"_id" : ObjectId("5810e15a762a39b41912a131"),
"validName" : "Eros",
"idUser" : ObjectId("1")
}
{
"_id" : ObjectId("5810e15a762a39b41912a132"),
"validName" : "Eros",
"idUser" : ObjectId("2")
}
I've already created a compound index to be able to search for the two values I want, such as this.
db.taxonomic.createIndex({"idUser":1,"validName":1})
Now, I want to be able to search and get a return from it only when both of the parameters are found on the same document of the collections, here's my try:
db.taxonomic.find({$text:{$search:"Eros 2"}},{idUser:1,validName:1})
The problem with this method is that it will return any match of "Eros" OR "2", what I want is a return of the values when "Eros" AND "2" are matched in a document of the collection.
Thank you for any help!
I dont think you require a text Index for it if you only want specific string
db.taxonomic.find({"$or" : [{"validName" : "Eros"},{"validName" : "2"}]},{idUser:1,validName:1})

MongoDB get object id by finding on another column value

I am new to querying dbs and especially mongodb.If I run :
db.<customers>.find({"contact_name: Anny Hatte"})
I get:
{
"_id" : ObjectId("55f7076079cebe83d0b3cffd"),
"company_name" : "Gap",
"contact_name" : "Anny Hatte",
"email" : "ahatte#gmail.com"
}
I wish to get the value of the "_id" attribute from this query result. How do I achieve that?
Similarly, if I have another collection, named items, with the following data:
{
"_id" : ObjectId("55f7076079cebe83d0b3d009"),
"_customer" : ObjectId("55f7076079cebe83d0b3cfda"),
"school" : "St. Patrick's"
}
Here, the "_customer" field is the "_id" of the customer collection (the previous collection). I wish to get the "_id", the "_customer" and the "school" field values for the record where "_customer" of items-collection equals "_id" of customers-collection.
How do I go about this?
I wish to get the value of the "_id" attribute from this query result.
How do I achieve that?
The find() method returns a cursor to the results, which you can iterate and retrieve the documents in the result set. You can do this using forEach().
var cursor = db.customers.find({"contact_name: Anny Hatte"});
cursor.forEach(function(customer){
//access all the attributes of the document here
var id = customer._id;
})
You could make use of the aggregation pipeline's $lookup stage that has been introduced as part of 3.2, to look up and fetch the matching rows in some other related collection.
db.customers.aggregate([
{$match:{"contact_name":"Anny Hatte"}},
{$lookup:{
"from":"items",
"localField":"_id",
"foreignField":"_customer",
"as":"items"
}}
])
In case you are using a previous version of mongodb where the stage is not supported, then, you would need to fire an extra query to lookup the items collection, for each customer.
db.customers.find(
{"contact_name":"Anny Hatte"}).map(function(customer){
customer["items"] = [];
db.items.find({"_customer":customer._id}).forEach(function(item){
customer.items.push(item);
})
return customer;
})

Search backward on MongoDb

I have 2 collection.
Collection "users"
{
"_id" : ObjectId("54b00098e0fdb6634b1f54e6"),
"state" : "active",
"backends" : [
DBRef("backends", ObjectId("54b001ebe0fd853df1c93419")),
DBRef("backends", ObjectId("54b00284e0fd853df1c9341b"))
]
}
Collection "backends"
{
"_id" : ObjectId("54b001ebe0fd853df1c93419"),
"state" : "running"
}
I want to get a list of backend of a user where the backend's state is "running".
How can mongodb do this like join two table?
Is it any method to search backward from backend or have function the filter?
I can search like this
db.users.find({"backends.$id" : "distring"})
But what if I want to search the state inside backend object? like.
db.users.find({"backends.$state" : "running"})
But ofcoure it is not working.
MongoDB doesn't support joins so you need to do this in two steps. In the shell:
var ids = db.backends.find({state: 'running'}, {_id: 1}).map(function(backend) {
return backend._id;
});
var users = db.users.find({'backends.$id': {$in: ids}}).toArray();
On a side note, you're probably better off using a plain ObjectId instead of a DBRef for the backends array elements unless the ids in that array can actually refer to docs in multiple collections.