Let\'s say i want to return the latest inserted document from the subdocument. I want to be able to return the second record within the tags array w/ the _id
of
Let say we have a category
as a document
and items
as a subdocument
.
// find document from collection
const category = await Category.findOne({ _id:'$hec453d235xhHe4Y' });
// fetch last index of sub-document
const lastIndexOfSubDoc: number = category.items.length - 1;
// here is the last item of sub-document
console.log(category.items[lastIndexOfSubDoc]);
as mongodb inserted the latest sub-document at last index, so we need to find the last index for the latest sub-doc.
Queries in MongoDB do not return subdocuments (or, as in your case, subdocuments of subdocuments). They match and return the the documents in the collection. The documents' shape can be changed a bit by projection, but it's limited. If you want to find the latest tag commonly, you probably want to make your documents represent tags. Having an array in an array is generally a bad idea in MongoDB, too.
If this is an uncommon operation, and one that doesn't need to be particularly fast, you can use an aggregation:
db.modules.aggregate([
{ "$unwind" : "$svn_branches" },
{ "$unwind" : "$svn_branches.tags" },
{ "$sort" : { "svn_branches.tags.updated_at" : -1 } },
{ "$group" : { "_id" : "$_id", "latest_tag" : { "$first" : "$svn_branches.tags" } } }
])
I needed to find the last entry of subdocuments and I managed to make it to work with the $slice
projection operator: mondodb.com > $slice (projection)
db.modules.find({_id:'ui', 'svn_branches.branch':'Rocky'},
{ 'svn_branches.tags': {$slice:-1} } )
I had only one level, if this doesn't work, please let me know.