Mongodb查询字段值,如果包含在长字符串中

时间:2016-03-16 16:41:17

标签: string mongodb include find

给定stringX = "term|quote|text"。我想对以下文件的mongodb进行查询:

[{
 id:"1",
 description:"term"
},
{
 id:"2",
 description:"term2"
},
{
 id:"3",
 description:"term3"
}]

如何找到id:1的文档?伪查询类似于:

"find document, which description is included (to be found) in stringX".

1 个答案:

答案 0 :(得分:1)

使用字符串中的$in运算符创建查询表达式。您的终极查询对象应该类似于:

var query = {
    "description": { "$in": ["term", "quote", "text"] }
}

或者,如果您更喜欢使用$or

var query = {
    "$or": [
        { "description": "term" },
        { "description": "quote" },
        { "description": "text" }
    ]
}

然后您可以在查询中使用

db.collection.find(query)

要以第一种形式获取查询, split() 输入字符串,并将管道作为分隔符,并将结果数组用作$in运算符的值:

var query = {
    "description": { "$in": stringX.split("|") }
};
db.collection.find(query)

对于第二种形式,请考虑在拆分字符串上使用 Array.map() 方法,如下所示

var orOperator = stringX.split("|").map(function (str){ return { "description": str } }),
    query = { "$or": orOperator };
db.collection.find(query)