本文介绍了寻找一种从另一个集合返回文档的方法,该集合基于另一个集合,MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我有两个集合,userssensors.用户看起来像:

To start with, I have two collections, users and sensors. A user looks like:

{
    "_id" : ObjectId("5d471ec414197a868de1b533"),
    "email" : "[email protected]",
    "hashedPassword" : "hash",
    "confirmation_code" : "conf",
    "confirmed" : true,
    "sensors" : [
        "asde22re",
    ]
}

传感器看起来像:

    "_id" : ObjectId("5d4c85d7b032b64f1c1a0b14"),
    "sensorId" : "asde22re",
    "data" : [
        {
            "data" : "10343",
            "time" : "2019-08-08T20:28:07.241Z"
        },
        {
            "data" : "11002",
            "time" : "2019-08-08T20:28:26.594Z"
        }
    ]

我有一个端点 GET/sensors,它应该返回用户也可以访问的所有传感器的数据,这可以在 users.sensors 中找到.

I have an endpoint GET /sensors, which is supposed to return data for all sensors of which a user has access too, this can be found in users.sensors.

我不确定如何真正用谷歌搜索我想要的东西(我可能无知),但本质上我需要一个查询,其中给定 users.email 它返回相应用户拥有的所有传感器访问也是.

I'm unsure how to actually google what I want (probably ignorance on my part), but essentially I need a query where given users.email it returns all the sensors that the respective user has access too.

我可以这样做的一种方法是:

One way I could do this is just by doing:

dbo.collection('users').findOne({ email: 'example_email' }) 然后使用此响应,获取 users.sensors 并执行 foreach 在集合中的每个传感器上,但这似乎效率低下.

dbo.collection('users').findOne({ email: 'example_email' }) and then using this response, get users.sensors and do a foreach on each sensor in the set, this seems inefficient though.

如何将其合并为一个查询?

How can I combine that into one query?

如果有帮助,这就是我想要复制的

If it helps, this is what I am trying to replicate

dbo.collection('users').findOne({ email }, { fields: { sensors: 1, _id: 0 } }, (err, results) => {

    if(err){
        return res.json({ err });
    }

    const { sensors } = results;

    dbo.collection('sensors').find({ sensorId: { $in: [sensors] } }).toArray((err, results) => {

        if(err){
            return res.json({ err });
        }

        return res.json({ results });

    });

});

推荐答案

类似于 sql 中的joins",在 Mongo 中你必须使用lookup".

Similar to "joins" in sql, in Mongo you have to use "lookup".

要使用查找,您必须使用聚合"查询,

To use lookup you have to use "aggregate" query,

所以你需要的查询是,

db.collection('users').aggregate({$match:{ email: 'example_email' }},
    {$unwind:{path:"$sensors"}},
    {$lookup:{from:"sensor", localField: "sensors", foreignField:"sensorId", as:"sensorDetails"}},
(err, userData)=>{
      console.log(userData);
})

那么这个查询在做什么,

So what this query is doing,

查看users"集合中的$lookup"行--->,它使用sensors"字段(本地字段到您的用户集合,如sql中的主ID)并从匹配到的sensor"集合中获取信息sensorId(传感器集合中的外部字段),并将结果存储在sensorDetails"字段中.

see "$lookup" line ---> from "users" collection, it is using "sensors" field (local field to your user collection like the primary id in sql) and fetch info from "sensor" collection matching to sensorId (foreign field in sensor collection), and store the result in "sensorDetails" field.

您可以通过userData[0].sensorDetails"访问sensorDetails.sensorDetails 将是数组.

you can have access to sensorDetails with "userData[0].sensorDetails".sensorDetails will be array.

查看关于查找的官方文档另请阅读unwind

Check official docs about lookupAlso read about unwind

这篇关于寻找一种从另一个集合返回文档的方法,该集合基于另一个集合,MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 06:21