繁体   English   中英

查找 mongodb 文档的数组中是否存在单个数组元素

[英]find whether individual array element exists in the mongodb document's array

有没有办法找到单个元素是否存在于 mongodb 文档的数组中。

例如:如果我有一个文件

{
    "_id": "A",
    "userId": "B",
    "selectedUsers": ["C", "D"]
}

我还有另一个数组 ["E", "C"]。
我想编写一个查询,当向它提供 userId 和上述数组时,该查询给出的结果为 [false, true],因为“E”不在 selectedUsers 数组中,而“C”在 selectedUsers 数组中。

我知道我可以先找到具有给定 userId 的文档,然后对它的单个元素使用 Array.find() 。 但我想知道在 mongodb 查询中是否有办法做到这一点。

另外,我正在使用 nodeJS 和猫鼬。

为了清楚起见,我需要使用 mongodb 查询获得与以下 js 代码相同的功能。

// req is the http request
// Selected is the mongoose Model for above document
// usersToCheck = ["E", "C"] (this is the second array)
const result = Selected.findOne({ userId: req.userId});
const { selectedUsers } = result;
const response = usersToCheck.map(uid => {
    if(selectedUsers.some(id => id === uid)){
        return true;
    }
    return false;
})

// response = [false, true]

现在,假设 usersToCheck 和 selectedUsers 的大小为 n,上述代码的复杂度为 O(n^2)。

我想知道如何使用 mongodb 查询获得与上述相同的响应。 因此,我可以根据 selectedUsers 数组索引集合并缩短获得响应所需的时间。

或者,任何其他改进上述代码的方法都值得赞赏。

在此先感谢您的帮助。

试试这个:

const result = Selected.aggregate([
  {
    $match: {
      userId: req.userId
    }
  },
  {
    $project: {
      _id: 0,
      result: {
        $map: {
          input: ["E", "C"],
          in: {
            $in: [
              "$$this",
              "$selectedUsers"
            ]
          }
        }
      }
    }
  }
]).exec();
const response = result[0].result;

蒙戈游乐场

你可以只使用$in

db.collection.find({selectedUsers: {$in: ["E", "C"]}})

这样的事情怎么样?

var input = ['E', 'C'];

db.collection.aggregate(
    [
        {
            $match: {
                _id: 'A'
            }
        },
        {
            $unwind: '$selectedUsers'
        },
        {
            $set: {
                has: { $in: ['$selectedUsers', input] }
            }
        },
        {
            $group: {
                _id: null,
                result: { $push: '$has' }
            }
        },
        {
            $project: {
                _id: 0
            }
        }
    ])

暂无
暂无

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

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