首页 > 解决方案 > Mongo db Collection find 从客户端的第一个条目而不是最后一个条目返回

问题描述

我正在使用 mongodb,我正在使用一些工作正常的条件查询数据库,但结果来自第一个条目到最后一个条目,因为我想从最后添加的条目查询到数据库中的集合

TaggedMessages.find({taggedList:{$elemMatch:{tagName:tagObj.tagValue}}}).fetch()

标签: mongodbmeteor

解决方案


Meteor 使用和的自定义包装版本,Mongo.CollectionMongo.Cursor支持开箱即用的反应性。它还抽象了 Mongo 查询 API,使其更易于使用。

这就是为什么从末端访问元素的本机方式在这里不起作用的原因。

在服务器上

为了$natural正确使用 Meteor,您可以在服务器上使用该hint属性作为选项(请参阅文档中的最后一个属性)

const selector = {
  taggedList:{ $elemMatch:{ tagName:tagObj.tagValue } }
}

const options = {
  hint: { $natural : -1 }
}

TaggedMessages.find(selector, options).fetch()

旁注:如果您需要访问“本机”Mongo 驱动程序,则需要使用rawCollection

在客户端

在客户端上,您无法真正访问 Mongo 驱动程序,而是访问看似相似的 API(称为minimongo包)。那里你不会$natural有空(可能在将来),所以你需要使用降序排序:

const selector = {
  taggedList:{ $elemMatch:{ tagName:tagObj.tagValue } }
}

const options = {
  sort: { createdAt: -1 }
}

TaggedMessages.find(selector, options).fetch()

推荐阅读