0

In a Mongo collection where the natural primary key would be given by two fields, let's say a and b, I was thinking of using the _id field as a subdocument containing the two fields.

As explained here, this is certainly a good solution if the queries always filter on both fields (and, unless I misunderstand, filter one specific value for both fields).

In my case they don't: I need to be able to filter separately by both fields. However, I can write stuff like this:

... .find({_id : { $eq: {a : 1} } })

which performs an object comparison, but even this:

... .find({_id : { $lt: {a : 1} } })

So my questions are:

  • what is the definition of the sorting of objects in MongoDB? I couldn't find anything in the documentation
  • assuming it is something reasonable like: compare all fields in their order, if the first n are equal and the (n+1)th are not, return the ordering of the (n+1)th; is this stable enough to actually use, or could it change in the future?

I would like to (reliably) use the index, instead of making a new one, at least the first of the two fields.

kenshin
  • 197
  • 10
  • Why does sorting matter here? Would you not be able to specify a sort condition like `.sort({ "_id.a": 1, "_id.b": 1 })` or something similar? I would certainly not recommend relying on the current (undocumented) sort order for fields that are of type object. – dnickless Oct 25 '17 at 15:49
  • I'm talking about the sorting according to which the $lt and $gt operators work. I agree I wouldn't rely on an undocumented feature. I was only hoping someone had more luck than me reading the docs – kenshin Oct 26 '17 at 07:19

0 Answers0