【问题标题】:How to query Array in MongoDB?如何在 MongoDB 中查询数组?
【发布时间】:2021-07-01 21:20:02
【问题描述】:

我是 MongoDB 新手,我有以下文档

{ "_id" : ObjectId("604b7d62b19a72a2b89028e6"), "name" : "ram", "tags" : [ "mobile", "iphone", "india" ] }
{"_id" : ObjectId("604b7d83b19a72a2b89028e7"), "name" : "shyam", "tags" : [ "mobile", "iphone", "india" ] }
{ "_id" : ObjectId("604b7d9bb19a72a2b89028e8"), "name" : "ravi", "tags" : [ "mobile", "android", "india" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "mobile", "android", "india" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "windows", "usa" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "tech", "apple", "microsoft" ] }

如何编写查询,以便如果我查询以下标签 ["mobile", "android", "12", "pro"] 我会得到以下结果

{ "_id" : ObjectId("604b7d9bb19a72a2b89028e8"), "name" : "ravi", "tags" : [ "mobile", "android", "india" ] }
{ "_id" : ObjectId("604b7db5b19a72a2b89028e9"), "name" : "aman", "tags" : [ "mobile", "android", "india" ] } 
{ "_id" : ObjectId("604b7d62b19a72a2b89028e6"), "name" : "ram", "tags" : [ "mobile", "iphone", "india" ] }
{ "_id" : ObjectId("604b7d83b19a72a2b89028e7"), "name" : "shyam", "tags" : [ "mobile", "iphone", "india" ] }

【问题讨论】:

  • 查询结果和sample out是一模一样的,能否详细说明一下对以下标签["mobile", "android", "12", "pro"]的查询?您想要与所有或任何一个匹配的文件吗?在示例文档中添加一些失败案例。
  • 好的,我添加了一些失败的案例。

标签: database mongodb mongoose nosql


【解决方案1】:

演示 - https://mongoplayground.net/p/EMW8xgV1yrU

使用$in

$in 运算符选择字段值等于指定数组中任何值的文档。要指定 $in 表达式,请使用以下原型:

db.collection.find({
  tags: { $in: [ "mobile", "android", "12", "pro" ] }
})

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2012-05-04
    • 2021-12-30
    相关资源
    最近更新 更多