I have a collection like
db.books.insertMany([
{"products" : [{"name": "name1", "ids": [4, 5, 6]}], "author" : "Dante", "shelf": "a" },
{ "products" : [{"name": "name1", "ids": [4, 5]}], "author" : "Homer", "shelf": "a" },
{ "products" : [{"name": "name1", "ids": [2]}], "author" : "Dante", "shelf": "b" },
])
and I want to retrieve all documents where "shelf" is ‘a’
and sort by 2 conditions:
1 – by Author
2 – documents where products.ids not contains 6 should be the first.
Could anyone help?
2
Answers
You can try this query:
$match
theshelf
value with "a".true
if 6 not exists intoproducts.ids
, otherwise false.$sort
by values you want.$project
to remove the auxiliar value.Example here
Here is a variation that sorts more granularly on author+"not containing 6".
which given this input set:
yields this result:
Optionally, this stage can be added after the
$sort
:And this will bring the sorted "not containing 6 then containing 6" items together again as an array packaged by
author
; the$push
retains the order. Note we need only needauthor
in_id
because the match was for one shelf. If more than one shelf is in the match, then we would need: