比较两个对象数组并检查它们是否具有公共元素

比较两个对象数组并检查它们是否具有公共元素

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

问题描述

如果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.

$setIntersectionFirstArray s Name s与SecondArray s Name s进行比较,并返回紧随其后的$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
    }
  }]
)

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

08-14 11:23