简体   繁体   English

如何编写一个从JavaScript数组中找到字段匹配的MongoDB查询

[英]How to write a MongoDB query that finds a field match from a JavaScript array

I'm trying to put together a MongoDB query that will return results where a field equals a value that is present in a JavaScript array. 我正在尝试将一个MongoDB查询放在一起,该查询将返回一个字段等于JavaScript数组中存在的值的结果。 I've put together the following code so far but it isn't working. 到目前为止,我已将以下代码放在一起,但它无法正常工作。 I would like the number field in the collection to find a match within the versions array. 我希望集合中的number字段在versions数组中找到匹配项。 I'm thinking that my "list" part using the $map under the first $project is wrong. 我想我在第一个$project下使用$map "list"部分是错误的。

//example data
var versions = ['v1', 'v2', 'v3'];

function getResults(versions) {

    var query =
    {
        "db": "db-name",
        "collection": "collection-name",
        "query":
        [
            {
                $match: {
                    time:  getStartTime(),
                }
            },
            {
                $project:
                {
                    number: "$number",
                    session_id: "$session_id",
                    round_id: "$_id",
                    "list": {
                        "$map": {
                            "input": { "$filter": {
                                "input": versions,
                                "as": "versions",
                                "cond": {
                                    "$eq": [ "$$versions.value", "$number" ]
                                }
                            }},
                            "as": "versions",
                            "in": "$$versions.value"
                        }
                    }

                }
            },
            {
                $group:
                {
                    _id: "$session_id",
                    number: { $first: "$list" },
                    rounds: { $addToSet: "$round_id" }
                }
            },
            {
                $project:
                {
                    number: "$number",
                    rounds: "$rounds"
                }
            }
        ]
    }
    return query;
}

Can you provide more info about you are triyng to do? 你能提供更多关于你的信息吗?

Maybe you can use filter by javascript array . 也许你可以使用javascript数组 过滤器

Here is an example code: 这是一个示例代码:

function isBigEnough(value) {
  return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

Maybe filter could be useful for you. 也许过滤器可能对您有用。

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

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