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"
}
}
添加回答
舉報