如何在 mongoDB 中搜索具有指定类型并包含特定值的文档

How to search documents which has specified type and contain specific value in mongoDB

我像这样在 mongodb 中插入了 3 个文档:

db.collection.insert({id:1, value:[1, 2, 3]})
db.collection.insert({id:2, value:[2, 4, 5]})
db.collection.insert({id:3, value:1})

那我想:

  1. 获取其值类型为数组且包含 1

  2. 的文档
  3. 获取其值包含或等于 1 或 2 或 5 的任何文档

谁能帮我解决这个问题?

I want to get the documents whose value's type is an Array and contains 1

使用 $type 运算符

db.collection.find({ "value": { "$type": 4 }, "value": 1})

I want to get any documents whose value contains or equal 1 or 2 or 5

使用 $in。引用文档

The $in operator selects the documents where the value of a field equals any value in the specified array.

db.collection.find({ "value": { "$in": [1,2,5] }})

您可以在一次查询中完成

db.collection.find({ 
    "$or": [
               { "value": { "$type": 4 }, "value": 1 }, 
               { "value" : { "$in": [1,2,5]}}
           ]
})