MongoDB查询对象的IN数组

编程入门 行业动态 更新时间:2024-10-28 08:18:23
本文介绍了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数组

本文发布于:2023-11-22 17:19:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!