在 Mongodb 中使用 .aggregate 相当于 findOne 什么? [英] What is the equivalent of findOne using .aggregate in Mongodb?

查看:77
本文介绍了在 Mongodb 中使用 .aggregate 相当于 findOne 什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我设法从集合中返回所有对象.例如,如何返回单个元素findOne({_ id:" 5e82d378527bb420a4001aaf ")?

Basically with this I manage to return all my objects from a collection. How can I return a single element, for example    in the style of findOne({_ id:" 5e82d378527bb420a4001aaf ")?

我知道如何使用 $match,但这会返回各种结果.

I know how to use $match, but this returns various results.

let _id="5e82d378527bb420a4001aaf"

Noticia.aggregate([
    {
        $addFields: {
            like: {
                $cond: [{ $in: [_id, "$likes"] }, true, false]
            },
            dislike: {
                $cond: [{ $in: [_id, "$dislikes"] }, true, false]
            }

        }
    }

], (err, noticia) => {

    // console.log(trans);
    if (err) {
        return res.status(400).json({
            ok: false,
            err
        });
    }
    return res.status(200).json({
        ok: true,
        data: noticia
    });

})

推荐答案

考虑一个示例 names 集合:

Consider a sample names collection:

{ _id: 1, name: "Jack", favoriteColor: "blue" },
{ _id: 2, name: "James", favoriteColor: "red" },
{ _id: 3, name: "John", favoriteColor: "blue" }

并使用 findOne 运行以下三个查询:

and run the following three queries using findOne:

db.names.findOne( { _id: 1 } )
db.names.findOne()
db.names.findOne( { favoriteColor : "blue" } )

三个查询的结果相同:

{ "_id" : 1, "name" : "Jack", "favoriteColor" : "blue" }


分别使用聚合的等效查询如下,结果相同:


The equivalent queries respectively using aggregation are the following, with the same result:

db.names.aggregate( [
  { $match: { _id: 1 } },
] )

db.names.aggregate( [
  { $limit: 1 }
] )


db.names.aggregate( [
  { $match: { "favoriteColor" : "blue" } },
  { $limit: 1 }
] )


db.collection.findOne 定义说 -

返回一个满足指定查询条件的文档集合或视图.如果多个文档满足查询,这方法根据自然顺序返回第一个文档反映磁盘上文档的顺序.

Returns one document that satisfies the specified query criteria on the collection or view. If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk.

使用 findOne 如果没有找到文档,则返回 null.但是 aggregation 返回一个游标,你可以应用 游标方法结果.

With findOne if no document is found it returns a null. But an aggregation returns a cursor, and you can apply the cursor methods on the result.

这篇关于在 Mongodb 中使用 .aggregate 相当于 findOne 什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆