【问题标题】:nodejs - how to search within last some documents in mongonodejs - 如何在 mongo 的最后一些文档中搜索
【发布时间】:2018-05-01 15:42:22
【问题描述】:

Nodejs

dbo.collection("abc")
    .find({"name": "Felicity"})
    .sort({_id:-1})
    .limit()
    .exec(
        function(err, results){

            // my code

        }
    );

集合中的数据

cansOne = [
   {
        "_id": ObjectId("5ace23558980..."),
        "name": "Khalichi",
        "gender": "F",
        "type":"Admin"
    },
    .
    .
    .

    {
        "_id": ObjectId("5ace23558980..."),
        "name": "Thore",
        "gender": "M",
        "type":""
    },
    {
        "_id": ObjectId("5ace23558980..."),
        "name": "John Snow",
        "gender": "M",
        "type":"Admin"
    },
    {
        "_id": ObjectId("5ace23558980..."),
        "name": "Felicity",
        "gender": "F",
        "type":"User"
    }
]

cansTwo = [
   {
        "_id": ObjectId("5ace23558980..."),
        "name": "Khalichi",
        "gender": "F",
        "type":"Admin"
    },
    .
    .
    .

    {
        "_id": ObjectId("5ace23558980..."),
        "name": "Thore",
        "gender": "M",
        "type":""
    },
    {
        "_id": ObjectId("5ace23558980..."),
        "name": "John Snow",
        "gender": "M",
        "type":"Admin"
    },
    {
        "_id": ObjectId("5ace23558980..."),
        "name": "Felicity",
        "gender": "F",
        "type":"User"
    }
    {
        "_id": ObjectId("5ace23558980..."),
        "name": "Batman",
        "gender": "M",a
        "type":""
    }
]

我收集了这种类型的数据。有两种情况:

1) "type":"" 在集合结束时,表示它是集合的最后一个文档。

2) 在"type":"" 文档之后,有一些文档在集合中。

我想搜索一个文档,但如果它在 "type":"" 文档的最后一个索引之后,那么它将返回该文档,否则它将返回 null。简而言之,我想在最后一个 "type":"" 之后的那些数据量中搜索这条记录

谁能帮忙。

提前致谢。

例如我要搜索"name": "Felicity"

预期输出

caseOne = [
    {
        "_id": ObjectId("5ace23558980..."),
        "name": "Felicity",
        "gender": "F",
        "type":"User"
    }
]

caseTwo = []

【问题讨论】:

  • 嗨维普尔;我可以问一下您在考虑的集合的顺序吗?因为如果您依赖于特定记录是否在另一条记录之后,这取决于您使用什么顺序列出文档。

标签: node.js mongodb


【解决方案1】:

您是尝试单独使用 Mongo 查询还是使用您的应用程序代码来执行此操作?单独的 Mongo 查询无法做到这一点,您无法找到一个文档,这取决于它与其他文档的相对位置。您需要将应用程序代码与 Mongo 查询一起使用,例如:

dbo.collection("abc").find({
    $or: [{
        name: "Felicity"
    }, {
        type: ""
    }]
})
.sort({
    _id: -1
})
.limit()
.exec(
    function(err, results) {
        // results here contains documents having name: Falicity or type: ""
        // do your check here

    }
);

【讨论】:

  • 不是这样,Felicity 来了两次,但如果它在最后一个 type = "" 之后我想要它,所以我不能使用或条件。
  • 如果你只编写 mongo 查询,它会有很大帮助。其他事情我会管理。感谢重播先生。
  • 正如我所说,这不能仅通过 Mongo 查询来完成。使用上面的代码,您需要编写更多代码处理results 以获得您需要的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多