Sort by reference document in Doctrine MongoDB ODM - mongodb

I'm using DoctrineMongoDBOBundle with Symfony2.
I've a Document Product which has an annotation referenceOne to other Document Price.
I want to sort by price when I fetch with queryBuilder.
$qb = $dm->createQueryBuilder('MyBundle:Product')
->field('geocoordinates')
->near('lat','lon')
->sort('hasPrice','desc')
But this doesn't works. Perhaps for the use of near?
It depends of toString() method of Document Price?
Regards.

I've a Document Product which has an annotation referenceOne to other Document Price.
There are no joins in MongoDB and I do not believe Doctrine does client side aggregation and sorting here. As such this wouldn't work anyway.
However sorting will work on a $near command ( http://docs.mongodb.org/manual/reference/operator/near/ ) which is what Doctrine should be using in this case, here you can see explicit support for $near being identified through the command you are using: https://github.com/doctrine/mongodb/commit/59f73cde2c15d171ff39afbf46c1a1339a51048c so your problem is the linked document, MongoDB has no JOINs.

In this case, hasPrice looks like it corresponds to a method, that perhaps checks whether the price reference is null or not. When referring to fields in ODM queries, names of class properties may be translated to the MongoDB field names (if they differ), but there is no support for method evaluation. Sammaye was correct that Doctrine does no client-side aggregation or sorting.
As an alternative, you may be able to sort on the price.$id field, which should group nonexistent values together in the results. Similarly, you could use the $exists operator to match/exclude based on whether a document was actual referenced. References in ODM (excluding the "Simple" type) are stored as MongoDBRef instances, which translate to objects with $id, $ref, and $db fields. As a result, you can query on those values just like any other field in your document.

Related

collection traversal order with mongoose methods like findOne() or findOneAndRemove()

How do mongoose methods like findOne() or findOneAndRemove() traverse a collection ? which object will this kind of methods return ? the oldest entry ? the first object from left to right in the collection ? do these methods sort collections by object id in ascending order during their execution ? or will it return a random object falling under the specified condition ? the Mongoose API Documentation just says "finds one document", it's probably obvious but it is not to me, hence this question ;)
[EDIT]
findOneAndRemove() documentation >>>
https://mongoosejs.com/docs/api.html#model_Model.findOneAndRemove
simply states ("Finds a matching document")
findOne() documentation >>>
https://mongoosejs.com/docs/api.html#model_Model.findOne
(simply states "Finds one document")
How can I be sure which document will be found by these methods if I have, lets say, two books in a books collection that have the same value under a "name" property ?
This question occured to me while running tests using mocha during my learning of MongoDB >>>
https://github.com/yactouat/JSNotions/blob/master/learningMongoDBMongoose/test/delete_test.js
Most driver functions correspond to Mongo DB's methods.
If you Google it a bit, you can find all Mongo shell's functions and their documentation.
For example, according to: findOne documentation on Mongo DB's site:
Returns one document that satisfies the specified query criteria on
the collection or view. If multiple documents satisfy the query, this
method returns the first document according to the natural order which
reflects the order of documents on the disk. In capped collections,
natural order is the same as insertion order. If no document satisfies
the query, the method returns null.

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.

mongodb EmbedMany strategy=set

I had a collection with an embedMany attribute using strategy=set, so an ArrayCollection was stored. However we deleted some items from the array and now there are some documents with keys not sequential integers.
I need to solve this inconsistence, how can I do that?
You could use $type operator and query for all documents where your embedManyField is of type object. Once you have these documents, apply array_values to fields where array shall be stored and save them again. Also to avoid such situations in future you should change your collection's strategy to either setArray or atomicSetArray.

mongodb computed field based on another query

I have a mongodb query, and I want to add a computed field. The computed field is based on where or not the item is in the results of another query. So my query returns the columns a,b,c,d, and then column e should be based on whether or not the current row would be matched by another query.
Is there an efficient way to do this in mongo? I'm not really sure how to do this one...
There is no way currently to execute a function as you describe within the database when returning a document via standard functions such as find. It's been requested by the community, but the general request is to operate only on a single document.
There are calculated fields using $project in the aggregation framework. But, they only operate on the current document in the pipeline. So, they can't summarize other queries.
You'll need to likely build your e value as part of your data access layer.

Mongodb - geospacial _id?

I currently have a collection of small documents. Each document has an indexed geospacial field and *the default _id is never used in any query*. There will never be more than one document related to a particular geo location. I think it makes sense to override the default _id, and use the geospacial data for this somehow.
Question is, how do you use geospacial data as the unique id? Is it a case of creating a flat string from the geo field? E.g. 'x123456y123456'?
The _id field is the unique identifier for each document and thus is a needed field. The _id field is generated on document creation automatically if one is not provided. If you can provide this geospaital value when creating the document you should be able to use the string as you suggested, you cannot use an array as the _id value. However please be aware that once a document is created the _id becomes unchangeable. This means that using the _id field as a meaningful index of geospatial data may not be of much value.
Have a look here for more info on the _id field and here for some information about creating geospatial indexes in Mongo