比较两个对象数组并检查它们是否有共同元素 [英] Comparing two object arrays and check if they have common elements

查看:13
本文介绍了比较两个对象数组并检查它们是否有共同元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 FirstArraySecondArray 在名称"字段中有共同元素,我如何在 MongoDB 中执行返回 _id 的查询?

How can I execute a query in MongoDB that returns _id if FirstArray and SecondArray has elements in common in "Name" field?

这是集合结构:

{
    "_id" : ObjectId("58b8d9e3b2b4e07bff8feed5"),
    "FirstArray" : [ 
        {
            "Name" : "A",
            "Something" : "200 ",
        }, 
        {
               "Name" : "GF",
            "Something" : "100 ",
        } 
    ],
    "SecondArray" : [ 
        {
            "Name" : "BC",
            "Something" : "200 ",
        }, 
        {
               "Name" : "A",
            "Something" : "100 ",
        }
    ]
}

推荐答案

3.6更新:

$match$expr 一起使用.$expr 允许在 $match 阶段使用聚合表达式.

Use $match with $expr. $expr allows use of aggregation expressions inside $match stage.

db.collection.aggregate([
  {"$match":{
    "$expr":{
      "$eq":[
        {"$size":{"$setIntersection":["$FirstArray.Name","$SecondArray.Name"]}},
        0
      ]
    }
  }},
  {"$project":{"_id":1}}
])

旧版本:

您可以尝试使用 $redact$setIntersection 进行查询.

You can try $redact with $setIntersection for your query.

$setIntersection 比较 FirstArrayNameSecondArrayNames 并返回公共名称文档数组,后跟 $size$redact 并将结果与​​ 0 进行比较以保留或删除文档.

$setIntersection to compare the FirstArrays Names with SecondArrays Names and return array of common names documents followed by $size and $redact and compare result with 0 to keep and else remove the document.

db.collection.aggregate(
  [{
    $redact: {
      $cond: {
        if: {
          $eq: [{
            $size: {
              $setIntersection: ["$FirstArray.Name", "$SecondArray.Name"]
            }
          }, 0]
        },
        then: "$$KEEP",
        else: "$$PRUNE"
      }
    }
  }, {
    $project: {
      _id: 1
    }
  }]
)

这篇关于比较两个对象数组并检查它们是否有共同元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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