Firestore: Save document ID into the Field - swift

I'm using Swift here and confused about how to save the document ID into itself field. Here is an example :
I have a collection named "menu"
here we can focus on the one and only document in the "menu" collection which saved the name field "ayam goreng". How do i save the document ID "
7D3fuw3fri6oj287SySW" to the field named "menu_id" inside the document?

As shown in the documentation on adding a document:
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():
let newCityRef = db.collection("cities").document()
// later...
newCityRef.setData([
// ...
])
In your case, you can then get the document ID from the new ref with:
newCityRef.documentId

Related

Add new field To collection in MongoDB but the value based on value in another field

How Can I add New Field To All Documents but Tha Value Based On value in Another Field?
Example :
{"_id":"1","city":"Amman"}
{"_id":"2","city":"Cairo"}
I Want to Add a new field to all documents (Capital) based on the city name if the city is Amman Capital will be true else false
I think what you trying to achieve is to add new field to each document based on the existing details in each of those document. Try this script with your collection details:
use YourDB;
db.YourCollection.find({}).forEach(function(doc){
if(doc.city =='whatever'){
doc.capital=true;
}else{
doc.capital=false;
}
db.YourCollection.save(doc);
});

Deleting a Reference in a MongoEngine ListField?

I have Mongoengine ORM that maps the following relationship, (simplified):
class UserInfo(mg.Document):
username = mg.StringField()
allcharacters = mg.ListField(mg.ReferenceField("Character"))
pass
class Character(mg.Document):
charid = mg.IntField()
pass
A User refers to an array of references to Character's. The problem is that when I access the User's allcharacter array and delete a reference:
for x in db.UserInfo.objects(username = session["user"])[0].allcharacters:
if x.charid == someint:
x.delete()
The document in question gets deleted but the reference in the array remains, pointing to a document that no longer exists.
I tried to
allcharacters = mg.ListField(
mg.ReferenceField("Character"), reverse_delete_rule=mg.CASCADE)
but that seems to do nothing.
How do I delete the entry in the ListField of an ListField(ReferenceField) in Mongoengine?
To guide future generations:
In order to delete the reference element from an array once the actual reference has been deleted, requires using the $pull operation.
char = db.Character.objects()[0]
objid = char.pk
char.delete()
user = db.UserInfo.objects().update_one(pull__allcharacters=objid)
Get a variable that points to the specific reference you want to delete. Use the .pk attribute to get it's ObjectId. You can now delete the document. To delete the reference in the array within the document, it's a pull query such that if the objid is in the array of allcharacters
May the future generation find this a solace.

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

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

Multi level MongoDB object querying by key

If you only know the key name (say "nickname"), but not the exact path to that key in the object.
e.g. nickname may be at the first level like:
{"nickname":"Howie"}
or at the second level:
{"user":{"nickname":"Howie"}}
Is it possible to query for nickname equal "Howie" that would return both documents?
Unfortunately there is no wild card that allows you to search for a field at any level in the db. If the position is not relevant and you can modify the document structure you have 2 choices here. You can store your document as
{ fieldname:"nickname", value : "Howie" }
{ fieldname:"user/nickname", value: "Howie" }
You can then query using
db.so.find({fieldname:/nickname/, value:"Howie"})
Alternatively you can store as
db.so.insert({value:"Howie", fieldpath:["nickname"]})
db.so.insert({value:"Howie", fieldpath:["user", "nickname"]})
The advantage with the second approach is that you can now index {fieldpath:1, value:1} and a query on it such as
db.so.find({fieldpath:"nickname", value:"Howie"})
will be an indexed query.