pymongo get rid of ObjectId - mongodb

I'm using pymongo to insert records into my mongodb database:
mongo = MongoClient('localhost',3001)
db = mongo.meteor
db.clients.insert({"hi":"test"})
the id of the inserted record is of type:
_id: ObjectId("57e92af647700265a2427f69")
is it possible to insert a record and generate an id as a string only without the Objectid?

You can just specify the _id on insert:
db.clients.insert({"hi":"test", "_id":"123"})

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.

Add a new unique ObjectId to each document in collection

I have an existing collection users where the _id field is a string instead of an ObjectId.
Is there a query that can update all documents in the collection and add a unique ObjectId for each document to using a new field called UID?
You can generate a new ObjectId using new ObjectId() in the shell.
db.users.find().forEach(function(doc){
doc.UID = new ObjectId();
db.users.save(doc);
})

How to pass variable between two queries in MongoDB?

I want to put the query result from one collection in a variable and use it as input for query in another collection. The queries look like this as follows:
Query 1:
var ID=db.User.findOne({Name:"Ivan"}, {ID: 1});
db.Artists.find({"Listeners.ID":ID});
Query 2:
var Friends=db.Users.find({Friends:x});
//Users.Friends is an array of interger identifier for User
db. Artists.find({"Listeners.ID":{$in:Friends}});
But they all don't work. How to write the right one?
The query db.User.findOne({Name:"Ivan"}, {ID: 1}); does not return a single value, it returns the document, reduced to the field you requested. What you get is an object, with two fields: _id (because you didn't explicitly exclude it) and ID (when it exists in the document). Your var ID looks like this:
{
_id:ObjectId(<long hex string>),
ID:<value>
}
So when you want to query by the ID value, you need to specify it:
db.Artists.find({"Listeners.ID":ID.ID});
Regarding your second query: when you use find instead of findOne you get a cursor object which can then be used to retrieve the individual documents using cursor.next() or cursor.toArray().

Update an array using Jongo

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();