Mongodb 如果包含在长字符串中,则查询字段值
Mongodb query on field value if included in long string
给定 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".
使用字符串中的 $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)
给定 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".
使用字符串中的 $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)