我的transactions
个收藏集中有以下文档。
{txnId: 1, amount: 200, tags:["monthly", "recharge"]},
{txnId: 2, amount: 4000, tags:["monthly", "salary"]},
{txnId: 3, amount: 1000, tags:["monthly", "waterbill"]},
{txnId: 4, amount: 400, tags:["monthly", "electricity"]},
{txnId: 5, amount: 300, tags:["dinner", "daily"]}
我想获取所有每月但 薪水
的文件我尝试了一些查询及其各自的输出:
查询1:
db.transactions.find({tags: {$elemMatch: {$in: ["monthly"], $nin: ["salary"]}}})
输出1:
{txnId: 1, amount: 200, tags:["monthly", "recharge"]}
{txnId: 2, amount: 4000, tags:["monthly", "salary"]}
{txnId: 3, amount: 1000, tags:["monthly", "waterbill"]}
{txnId: 4, amount: 400, tags:["monthly", "electricity"]}
查询2:
db.transactions.find({tags: {$nin: ["salary"]}})
输出2:
{txnId: 1, amount: 200, tags:["monthly", "recharge"]}
{txnId: 3, amount: 1000, tags:["monthly", "waterbill"]}
{txnId: 4, amount: 400, tags:["monthly", "electricity"]}
{txnId: 5, amount: 300, tags:["dinner", "daily"]}
查询3:
db.transactions.find({tags: {$nin: ["salary"]}, tags: {$elemMatch: {$in: ["monthly"]}}})
输出3:
{txnId: 1, amount: 200, tags:["monthly", "recharge"]}
{txnId: 2, amount: 4000, tags:["monthly", "salary"]}
{txnId: 3, amount: 1000, tags:["monthly", "waterbill"]}
{txnId: 4, amount: 400, tags:["monthly", "electricity"]}
为什么 $ in 和 $ nin 没有合作,甚至$ nin没有按预期工作?还是我误解了?
答案 0 :(得分:1)
你可以使用$ nin& $ in in together。以下查询将给出预期记录。希望不要使用$ elemMatch。
db.transactions.find({$and:[{tags:{$in:['monthly']}}, {tags:{$nin:['salary']}}]}).toArray()
<强>输出:强>
[
{txnId: 1, amount: 200, tags:["monthly", "recharge"]},
{txnId: 3, amount: 1000, tags:["monthly", "waterbill"]},
{txnId: 4, amount: 400, tags:["monthly", "electricity"]}
]