简体   繁体   English

Mongo DB查询公式

[英]Mongo db query formulation

I have a database that has the following collection: 我有一个具有以下集合的数据库:

{id1: "1", id2: "a"}, {id1: "2", id2: "a"}, {id1: "3", id2: "a"}, {id1: "1", id2: "b"}, {id1: "2", id2: "b"}

I want to find id2 given the list of id1 : 1,2 我想找到id2给定id1的列表:1,2

the answer given should be b given that it is the only id2 that has ONLY 1,2 给出的答案应该是b因为它是唯一具有1,2 id2

If the list of 'id1' given were: 1,2,3 then the 'id2' found should be 'a' given that 'a' is associated with 1,2 AND 3 如果给定的“ id1”的列表为:1、2、3,则假定“ a”与1,2 AND 3相关联,则找到的“ id2”应为“ a”

How do I query this on Mongodb preferably using aggregation. 我如何在Mongodb上查询此查询,最好使用聚合。

I think I understand what you're trying to do. 我想我了解您正在尝试做的事情。 You can do it with an aggregate query, but it isn't very straight forward: 您可以使用汇总查询来做到这一点,但这不是很简单:

db.<collection_name>.aggregate([
    {$group:{_id:"$id2",id1Set:{$addToSet:"$id1"}}},
    {$match:{"id1Set":{$size:2,$all:["1","2"]}}}
])

This query will group the documents by id2 and create a set containing the values of id1. 该查询将按id2对文档进行分组,并创建一个包含id1值的集合。 It then matches the documents from the group, looking at the size of the id1Set (should be 2) and the values in the id1Set should contain all of "1" and "2". 然后,它与该组中的文档匹配,查看id1Set的大小(应为2),并且id1Set中的值应包含“ 1”和“ 2”的所有值。

Since your example data contains string values for id2 ("1" and "2", rather than 1 and 2) the match is on string values rather than numbers. 由于示例数据包含id2的字符串值(“ 1”和“ 2”,而不是1和2),因此匹配项是字符串值而不是数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM