【问题标题】:How can I provide multiple criteria for an attribute within an element of array in mongo query?如何在 mongo 查询中为数组元素中的属性提供多个条件?
【发布时间】:2015-05-15 08:45:03
【问题描述】:

我有一个包含以下文档的集合:


    {
       "_id": 1,  
       "books": [  
         {  
           "id":"Sherlock Holmes",  
           "category":"Novel"  
         },  
         {  
           "id":"10 tips for cook",  
           "category":"Tips"  
         }  
       ]  
    },  
    {  
       "_id": 2,  
       "books": [    
         {
           "id":"10 tips for cook",  
           "category":"Tips"
         }  
        ]  
    },  
    {
       "_id": 3,  
       "books": [  
         {  
           "id":"Sherlock Holmes",  
           "category":"Novel"  
         }  
       ]  
    }

我要查询的文档包含 id 为“Sherlock Holmes”和“10 Tips for cook”的书籍,其中“_id”为 1。

我尝试过使用 $in 和 $elemMatch,但结果是这三个。在这种情况下我只需要一个。

你有什么解决办法吗?

【问题讨论】:

  • 您使用的是哪个 MongoDB 版本?
  • 我使用的是 MongoDB v2.4.5

标签: arrays mongodb


【解决方案1】:

使用$and 运算符搜索具有多个表达式的同一字段。

db.coll.find({
    '$and': [
        {'books.id': 'Sherlock Holmes'},
        {'books.id': '10 tips for cook'}
    ]
})

结果:

{
    "_id" : 1,
    "books" : [ 
        {
            "id" : "Sherlock Holmes",
            "category" : "Novel"
        }, 
        {
            "id" : "10 tips for cook",
            "category" : "Tips"
        }
    ]
}

【讨论】:

    【解决方案2】:

    因为 _id 在 MongoDB 集合中是唯一的,所以可以直接查询

    db.myCollection.find({_id:1})
    

    如果你不想返回整个文档,你可以使用投影

    db.myCollection.find({_id:1},{_id:0, books:1})

    【讨论】:

    • 我需要它返回一个符合我的条件的列表。结果应该是一个列表。在这种情况下,列表只包含一个元素:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2021-09-04
    • 1970-01-01
    • 2011-03-19
    • 2017-04-12
    • 1970-01-01
    相关资源
    最近更新 更多