MongoDB查询对象的IN数组 [英] MongoDB query IN array of object

查看:91
本文介绍了MongoDB查询对象的IN数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在检索两个馆藏之间的信息时遇到问题.第一个集合存储员工信息:

I have problem to retrieve information between two collections. The first collection stores employees information:

{
        "_id" : ObjectId("4f9643967f8b9a3f0a00005a"),
        "birth_date" : "1963-09-09",
        "departments" : [
                {
                        "departments_id" : ObjectId("4f9643957f8b9a3f0a000007"),
                        "from_date" : "1990-01-03",
                        "to_date" : "1990-01-15"
                }
        ],
        "first_name" : "Parviz",
        "gender" : "M",
        "hire_date" : "1990-01-03",
        "last_name" : "Lortz",
}

第二个部门信息

{
        "_id" : ObjectId("4f9643957f8b9a3f0a000004"),
        "dept_name" : "Marketing",
        "managers" : [
                {
                        "employees_id" : ObjectId("4f96439b7f8b9a3f0a0186a9"),
                        "from_date" : "1985-01-01",
                        "to_date" : "1991-10-01"
                },
                {
                        "employees_id" : ObjectId("4f96439b7f8b9a3f0a0186aa"),
                        "from_date" : "1991-10-01",
                        "to_date" : "9999-01-01"
                }
        ]
}

我尝试查找:给定员工的所有部门.

我尝试过类似的事情:

employees = db.employees.find({_id:ObjectId("some_id")});
db.departments.find({_id:{$in:...}});

但是我不知道如何从var员工那里解释所有部门的department_id.

But I don't know how I can explain $in department_id of all departments from var employees.

推荐答案

这不能通过简单的查询来完成.您将必须遍历employees.departments,并为每次迭代将其department_id添加到数组中.然后,您可以在第二行中使用此数组.这是您选择的语言中最好的方法.

This can not be done with a simple query. You will have to loop over employees.departments and for each iteration add its departments_id to an array. This array you then can use in your second line. This is something best done in your language of choice.

为了使此操作更容易,您必须更改架构.一种选择是将部门信息存储在员工记录中,但是在您的情况下,您将要复制大量数据.

In order to make this easier, you'll have to change your schema. One option is to store the department information in the employee record, but in your case you'd be duplicating a lot of data.

相反,我建议让每个部门都包含一个带有员工ID和日期的列表,如下所示:

I would instead suggest to have each department contain a list with employee IDs and dates instead like this:

{
        "_id" : ObjectId("4f9643957f8b9a3f0a000004"),
        "dept_name" : "Marketing",
        "managers" : [
        ]
        "employees" : [
            {
                    "employee_id" : ObjectId("4f9643967f8b9a3f0a00005a"),
                    "from_date" : "1990-01-03",
                    "to_date" : "1990-01-15"
            }
        ]
}

在这种情况下,您可以简单地运行:

In that case, you can then simply run:

db.departments.find( { "employees.employee_id": ObjectId("some_id") } );

这篇关于MongoDB查询对象的IN数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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