3 回答

TA贡献1795条经验 获得超7个赞
试试这个:
targetObj = await db.db(MDBC.db).collection(MDBC.pC)
.aggregate([
{
$match: {
$and: [
{
$or: [
{ "profession.organization": "bank" },
{ "profession.city": "NY" }
]
},
{
$or: [
{
"profession.organization": "bank",
"profession.city": { $ne: "NY" }
},
{
"profession.organization": { $ne: "bank" },
"profession.city": "NY"
}
]
}
]
}
},
{ $sample: {size: 1} } ]).next();

TA贡献1789条经验 获得超8个赞
不幸的是,在撰写本文时,MongoDB 中没有匹配的运算符来帮助解决这个问题。$or但是您可以通过组合and运算符来获得类似的结果$ne。为您的查询尝试这样的事情:
const query = {
$or: [
{
// Include all non-banks outside of NY.
'profession.city': { $ne: 'NY' },
'profession.organization': { $ne: 'bank' }
},
{
// Include all non-banks in NY.
'profession.city': 'NY',
'profession.organization': { $ne: 'bank' }
},
{
// Include all banks outside of NY.
'profession.city': { $ne: 'NY' },
'profession.organization': 'bank'
}
]
};

TA贡献1828条经验 获得超3个赞
我认为在接受的答案中使用的查询可能要短得多。
db.collection.aggregate([
{
$match: {
$or: [
{
"profession.organization": "bank",
"profession.city": {
$ne: "NY"
}
},
{
"profession.organization": {
$ne: "bank"
},
"profession.city": "NY"
}
]
}
},
{
$sample: {
size: 1
}
}
])
我还要说的一件事是,如果您还想包含不具有这两个属性中的任何一个的文档,那么您应该使用它:
db.collection.aggregate([
{
$match: {
$or: [
{
"profession.organization": "bank",
"profession.city": {
$ne: "NY"
}
},
{
"profession.organization": {
$ne: "bank"
},
"profession.city": "NY"
},
{
"profession.organization": {
$ne: "bank"
},
"profession.city": {
$ne: "NY"
}
}
]
}
},
{
$sample: {
size: 1
}
}
])
这还将包括文件,如 -
{
"profession": {
"organization": "someBank",
"city": "notNA"
}
}
添加回答
举报