【发布时间】:2020-02-20 16:22:25
【问题描述】:
我有以下收藏:
{ "_id" : ObjectId("5e4e3e068438c24cdec0eeb9"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eeba"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc", "efg" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebb"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : "0xmd5md5md5" }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebc"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123 ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebd"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : 123 }
“extraid”字段是数字或数组,当我在下面运行操作时,返回的结果不是我想要的:
> db.foo.find({"extraid": 123})
{ "_id" : ObjectId("5e4e3e068438c24cdec0eeb9"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eeba"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc", "efg" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebc"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123 ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebd"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : 123 }
我认为只有一个文档匹配,这是我的预期结果:
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebd"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : 123 }
我也尝试运行$type 运算符,以便它可以完全匹配,但结果仍然不是我想要的:
> db.foo.find({"extraid": {"$eq": 123, "$type":"int"}})
{ "_id" : ObjectId("5e4e3e068438c24cdec0eeb9"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eeba"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc", "efg" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebc"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123 ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebd"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : 123 }
> db.foo.find({"extraid": {"$eq": 123, "$type":"array"}})
{ "_id" : ObjectId("5e4e3e068438c24cdec0eeb9"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eeba"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123, "abc", "efg" ] }
{ "_id" : ObjectId("5e4e3e078438c24cdec0eebc"), "from" : "0xabsdfeeqwsfdasfafaefegr", "to" : "0xfdshshrtfafdfadfaete", "extraid" : [ 123 ] }
>
$type: array可以匹配所有'extraid'的数组类型,但是$type: int不行。
那么谁知道如何检索与类型为数字或数组的字段完全匹配的文档?
【问题讨论】:
标签: mongodb mongodb-query