【问题标题】:mongodb find exact documentmongodb找到确切的文件
【发布时间】:2014-02-03 20:57:42
【问题描述】:

我正在 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)

【问题讨论】:

  • 您能否将此问题重命名为“mongodb remove document from array that is an exact match”或类似的名称?我正在寻找您最初问题的答案,但很失望地发现实际问题与数组有关。谢谢!仅供来这里寻找最初问题答案的人们参考:stackoverflow.com/questions/27993275/…

标签: mongodb find pull


【解决方案1】:

没有很好的文档记录,但是如果您使用$pullAll 而不是$pull,则只会删除完全匹配的元素:

db.test.update({}, {$pullAll:{a: [{b:1,c:2}]}});

【讨论】:

  • 哇,你说得对!奇怪的行为......但谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2014-04-03
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多