我正在MongoDB中寻找一种查找确切文档的方法,这意味着我不想将文档与预期之外的其他字段进行匹配。
这是我可以对子文档执行的操作
> db.test.insert({a:{b:1,c:2}});
> db.test.insert({a:{b:1}});
> db.test.find({'a.b':1}); // non exact match
{a:{b:1,c:2}}
{a:{b:1}}
> db.test.find({'a':{'b':1}}); // exact match
{a:{b:1}}
我想对主文档(而不是子文档)执行相同的操作。但
> db.test.insert({b:1,c:2});
> db.test.insert({b:1});
> db.test.find({'b':1}); // non exact match
{a:{b:1,c:2}}
{a:{b:1}}
> db.test.find({'.':{'b':1}}); // does not work :(
> db.test.find({'b':1, 'c':null}); // works, but how I am supposed to know that 'c' could exists ???
{a:{b:1}}
最终目标是$pull
对数组执行此操作
> db.test.insert({a:[{b:1,c:2},{b:1,d:3},{b:1,c:2},{b:1,c:2,d:3}]});
> db.test.update({}, {$pull:{'a':{b:1,c:2}}});
> db.test.find();
{a:[{b:1,d:3}]} // NOOOO :'(
有人对此有想法吗?
编辑:
这是我在数组上找到的精确/部分匹配的一些精度:
db.test.find({'a':{b:1,c:2}});
db.test.find({'a':{$elemMatch:{b:1,c:2}}});
db.test.update({}, {$pull:{'a':{b:1,c:2}}})
db.test.update({}, {$pullAll:{'a':[{b:1,c:2}]}})
感谢JohnnyHK)它没有很好的文档记录,但是如果您使用$pullAll
而不是$pull
,则只会删除完全匹配的元素:
db.test.update({}, {$pullAll:{a: [{b:1,c:2}]}});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句