简体   繁体   English

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

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

Is there a way to find whether the individual element exists in the mongodb document's array.有没有办法找到单个元素是否存在于 mongodb 文档的数组中。

For Example: If I have a document例如:如果我有一个文件

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

and I have another array as ["E", "C"].我还有另一个数组 ["E", "C"]。
I want to write a query which gives the result as [false, true] when userId and the above array is supplied to it because "E" is not in the selectedUsers array and "C" is in the selectedUsers array.我想编写一个查询,当向它提供 userId 和上述数组时,该查询给出的结果为 [false, true],因为“E”不在 selectedUsers 数组中,而“C”在 selectedUsers 数组中。

I Know I can just first find the document with the given userId and then use Array.find() on it for individual element.我知道我可以先找到具有给定 userId 的文档,然后对它的单个元素使用 Array.find() 。 But I want to know if there's a way to do this in mongodb query.但我想知道在 mongodb 查询中是否有办法做到这一点。

Also, I am using nodeJS and mongoose.另外,我正在使用 nodeJS 和猫鼬。

Just to be clear I need to get the same functionality as the below js code using mongodb query.为了清楚起见,我需要使用 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]

Now the above code have a complexity of O(n^2) assuming the size of usersToCheck and selectedUsers is n.现在,假设 usersToCheck 和 selectedUsers 的大小为 n,上述代码的复杂度为 O(n^2)。

I want to some how get the same response as above using mongodb query.我想知道如何使用 mongodb 查询获得与上述相同的响应。 So, that I can index the collection based on the selectedUsers array and improve the time required to get the response.因此,我可以根据 selectedUsers 数组索引集合并缩短获得响应所需的时间。

Or, any other way to improve the above code is appreciated.或者,任何其他改进上述代码的方法都值得赞赏。

Thanks in advance for your help.在此先感谢您的帮助。

Try this one:试试这个:

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;

MongoPlayground蒙戈游乐场

你可以只使用$in

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

how about something like this?这样的事情怎么样?

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