我怎样才能执行下面的 mongo 数据库查询
How can i execute below mongo db query
{
"$and":[ {
"mobile_nos":{
"$regex":{
"regex":"^((?!Nagpur).)*$",
"flags":"i"
}
}
},
{
"full_name":{
"$regex":{
"regex":"^((?!pune).)*$",
"flags":"i"
}
}
}
]
}
以上 MongoDB 查询没有产生任何结果,因为文档中不存在 mobile_nos
字段。
如果字段不存在于文档中,我该如何更改查询以returns得到结果?
{
"$and":[ {
$or:[
{
"mobile_nos":{
"$regex":{
"regex":"^((?!Nagpur).)*$",
"flags":"i"
}
},
{
"mobile_nos":{
$exists: false
}
}
]
}
},
{
"full_name":{
"$regex":{
"regex":"^((?!pune).)*$",
"flags":"i"
}
}
}
]
}
您可以尝试使用 $or
operator for the logical condition that use the regex search if the the field exists OR don't use it if the field does not exist (with the $exists
运算符的以下查询)。
无需指定 $and
operator in the case since MongoDB provides an implicit AND
operation when specifying a comma separated list of expressions. Using an explicit AND
with the $and
必须在多个表达式中指定相同的字段或运算符时才需要运算符:
{
"$or": [
{
"mobile_nos": {
"$regex": {
"regex": "^((?!Nagpur).)*$",
"flags": "i"
}
}
},
{ "mobile_nos": { "$exists": false } }
],
"full_name": {
"$regex": {
"regex": "^((?!pune).)*$",
"flags": "i"
}
}
}
{
"$and":[ {
"mobile_nos":{
"$regex":{
"regex":"^((?!Nagpur).)*$",
"flags":"i"
}
}
},
{
"full_name":{
"$regex":{
"regex":"^((?!pune).)*$",
"flags":"i"
}
}
}
]
}
以上 MongoDB 查询没有产生任何结果,因为文档中不存在 mobile_nos
字段。
如果字段不存在于文档中,我该如何更改查询以returns得到结果?
{
"$and":[ {
$or:[
{
"mobile_nos":{
"$regex":{
"regex":"^((?!Nagpur).)*$",
"flags":"i"
}
},
{
"mobile_nos":{
$exists: false
}
}
]
}
},
{
"full_name":{
"$regex":{
"regex":"^((?!pune).)*$",
"flags":"i"
}
}
}
]
}
您可以尝试使用 $or
operator for the logical condition that use the regex search if the the field exists OR don't use it if the field does not exist (with the $exists
运算符的以下查询)。
无需指定 $and
operator in the case since MongoDB provides an implicit AND
operation when specifying a comma separated list of expressions. Using an explicit AND
with the $and
必须在多个表达式中指定相同的字段或运算符时才需要运算符:
{
"$or": [
{
"mobile_nos": {
"$regex": {
"regex": "^((?!Nagpur).)*$",
"flags": "i"
}
}
},
{ "mobile_nos": { "$exists": false } }
],
"full_name": {
"$regex": {
"regex": "^((?!pune).)*$",
"flags": "i"
}
}
}