Golang take nested value from mongo.SingleResult - mongodb

In Golang I read a value from a database.
findOptions := options.FindOneOptions{}
findOptions.SetSort(bson.D{{"foo", -1}})
var valueFromDatabase *mongo.SingleResult
valueFromDatabase = clients.MongoClient.Database("foo").Collection("foo").FindOne(context.TODO(), bson.M{})
Is it possible to get a specific position, much like you would in an array?
Not working sample code, how it should fetch the values:
valueFromDatabase.NestedObject.Array[0].Value
Background is. A generic approach should be used so that the solution works independently of the structure of the BSON document. Which fields are to be read out is known from a slice.
The following approach was tried: The conversion to a json destroys the Mongo encryption.

Related

How can I perform a bulkWrite in mongodb using rust mongodb driver?

I am implementing a process in rust where I read a large number of documents from a mongodb collection, perform some calculations on the values of each document and then have to update the documents in mongodb.
In my initial implementation, after the calculations are performed, I go through each of the documents and call db.collection.replace_one.
let document = bson::to_document(&item).unwrap();
let filter = doc! { "_id": item.id.as_ref().unwrap() };
let result = my_collection.replace_one(filter, rec_document, None).await?
Since this is quite time consuming for large record sets, I want to implement it using db.collection.bulkWrite. In version 1.1.1 of the official rust mongodb driver, bulkWrite does not seem to be supported, so I want to use db.run_command. However, I am not sure how to call db.collection.bulkWrite(...) using run_command as I cannot figure out how to pass the command name as well as the set of documents to replace the values in mongodb.
What I have attempted is to create a String representing the command document with all the document records to be updated string joined as well. In order to create bson::Document from that string, I convert the string to bytes and then attempt to create the document to be passed using Document::from_reader but that doesn't work, nor is a good solution.
Is there a proper or better way to call bulkWrite using version 1.1.1 of the mongodb crate?

Firestore: get an Observable doc from another field which is not the Id

I want to get a single Observable from a collection, but I want to get it from a different field that is not the id. It is possible?
I do not want to do a query and limit to 1. I need to get a Single Observable not an array Observable.
Schema:
Code:
this.afs.doc<Credit>('credits/uid/'+ uid).valueChanges();
Error:
Invalid document reference. Document references must have an even number of segments, but credits/uid/d1Zt8sozYqb6H27lhoJgF1Gx2Cc2 has 3
I am not sure if I understand correctly, but I guess that you want to get document with particular uid field value, not using document id.
This particular error is related with common feature of Firestore, that every document has to be in collection not in document. So path values for documents, (nested as well) are always checked, if the segments (devided by /) number is even ex. collection1/doc1/collection2/doc2/collection3/doc3
As results in your code we have 3 segments (like credits/uid/<uid_value>) so this is the error.
I am not very familiar with angularFire2 itself, but I have done it in JS. The approach is normally to query collection and than use method on the results, which in classic JS returns Query object on which the same methods can be used as on CollectionReference (which extends 'Query' btw - reference 1).
Combining this approach with those references: querying and collection I propose following solution:
this.afs.collection('credits', ref => ref.where('uid', '==', <uid_value>)).valueChanges()
If uid_value will be unique you should get your doc.
Unfortunately I do not have any playground to test the solution so please let me know how it works - or if there will be any additional errors.
I hope it will help! Good Luck!

How to order the fields of the documents returned by the find query in MongoDB? [duplicate]

I am using PyMongo to insert data (title, description, phone_number ...) into MongoDB. However, when I use mongo client to view the data, it displays the properties in a strange order. Specifically, phone_number property is displayed first, followed by title and then comes description. Is there some way I can force a particular order?
The above question and answer are quite old. Anyhow, if somebody visits this I feel like I should add:
This answer is completely wrong. Actually in Mongo Documents ARE ordered key-value pairs. However when using pymongo it will use python dicts for documents which indeed are not ordered (as of cpython 3.6 python dicts retain order, however this is considered an implementation detail). But this is a limitation of the pymongo driver.
Be aware, that this limitation actually impacts the usability. If you query the db for a subdocument it will only match if the order of the key-values pairs is correct.
Just try the following code yourself:
from pymongo import MongoClient
db = MongoClient().testdb
col = db.testcol
subdoc = {
'field1': 1,
'field2': 2,
'filed3': 3
}
document = {
'subdoc': subdoc
}
col.insert_one(document)
print(col.find({'subdoc': subdoc}).count())
Each time this code gets executed the 'same' document is added to the collection. Thus, each time we run this code snippet the printed value 'should' increase by one. It does not because find only maches subdocuemnts with the correct ordering but python dicts just insert the subdoc in arbitrary order.
see the following answer how to use ordered dict to overcome this: https://stackoverflow.com/a/30787769/4273834
Original answer (2013):
MongoDB documents are BSON objects, unordered dictionaries of key-value pairs. So, you can't rely on or set a specific fields order. The only thing you can operate is which fields to display and which not to, see docs on find's projection argument.
Also see related questions on SO:
MongoDB field order and document position change after update
Can MongoDB and its drivers preserve the ordering of document elements
Ordering fields from find query with projection
Hope that helps.

Using timestamps in a find query with mgo

I'm trying to run a fairly simple query using MGO that only has one condition included: published field must be less than or equal to the current time.
I have a test document in my database that was created as follows:
db.articles.insert([{
"title": "Woo this is a test title",
"published": ISODate("2017-01-02T12:00:00Z")
}])
My querying code is:
now := time.Now().Format(time.RFC3339)
articlesCollection.Find(bson.M{"published": bson.M{"$lte": now}}).
Sort("-published").All(&frontPageArticles.Articles)
But I get no records returned.
I'm comfortable with Mongo, but very new to Go (and thus mgo) - I'm sure I'm doing something wrong at a basic level, but am not sure what. Can anyone help?
The solution is simple: don't format your time, just pass a time.Time value:
now := time.Now()
The mgo package will encode the time in the appropriate format. In your example you passed the time as a string which would only work if the published field in MongoDB would also be a string in the same format (and not a MongoDB date).

Pymongo returns subdocs as dicts instead of SONs?

Is there a way to have pymongo return subdocs as SONs so they can be successfully passed back in for find queries? GridFS is returning the file._id as a dict instead of a SON; so, the subsequent call to grid_file.GridOut.read is failing to find the grid file. (I know, using dicts as _id is asking for trouble, but I'm dealing w/ an existing db/system.)
I don't see how I can intervene to coerce the file._id into the correctly ordered SON.
The MongoClient.document_class field controls this! Just add document_class=bson.son.SON, to the constructor