如何检查一个数组字段是否是MongoDB中另一个数组的一部分? [英] How to check if an array field is a part of another array in MongoDB?

查看:38
本文介绍了如何检查一个数组字段是否是MongoDB中另一个数组的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此

In this question, Jeff the Bear explained how to search documents with an array

contains 'tag1'
contains ['tag1','tag2'],
contains any of ['tag3', 'tag4']

但是,如果我要使用另一个数组的一部分来搜索文档,该怎么办?

But how should I do if I want to search documents with an array which is part of another array?

post1.tags = ['tag1']
post2.tags = ['tag1','tag3']
post3.tags = ['tag2','tag4']
post4.tags = ['tag1','tag2','tag3','tag4']

我想获取post1和post3,因为它们具有标签

I want to get post1 and post3 because they have tags

contained in ['tag1', 'tag2', 'tag4']

我不想获取post2和post4,因为['tag1', 'tag2', 'tag4']

I don't want to get post2 and post4, because tag3 doesn't exist in ['tag1', 'tag2', 'tag4']

换句话说,选择可以在另一个条件数组中找到其标签数组中所有元素的帖子

In other words, select posts that all elements in its tags array can be found in another conditional array

推荐答案

您可以使用聚合框架来执行此操作.给出以下数据

You can use aggregation framework to do this. Given the following data

> db.post.find()
{ "_id" : 1, "tags" : [ "tag1" ] }
{ "_id" : 2, "tags" : [ "tag1", "tag3" ] }
{ "_id" : 3, "tags" : [ "tag2", "tag4" ] }
{ "_id" : 4, "tags" : [ "tag1", "tag2", "tag3", "tag4" ] }

聚合查询

db.post.aggregate({
  $project: {
    _id: 1,
    tags: 1,
    killFlag: {
      $const: [true, false]
    }
  }
}, {
  $unwind: "$tags"
}, {
  $unwind: "$killFlag"
}, {
  $match: {
    $nor: [{
        tags: {
          $in: ['tag1', 'tag2', 'tag4']
        },
        killFlag: true
      }
    ]
  }
}, {
  $group: {
    _id: "$_id",
    tags: {
      $addToSet: "$tags"
    },
    killFlag: {
      $max: "$killFlag"
    }
  }
}, {
  $match: {
    killFlag: false
  }
}, {
  $project: {
    _id: 1,
    tags: 1
  }
})

会给你

{
  "result": [{
      "_id": 3,
      "tags": [
          "tag4",
          "tag2"
      ]
    }, {
      "_id": 1,
      "tags": [
          "tag1"
      ]
    }
  ],
  "ok": 1
}

这篇关于如何检查一个数组字段是否是MongoDB中另一个数组的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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