【问题标题】:Mongoose: find mixed schema type documents with multiple entriesMongoose:查找具有多个条目的混合模式类型文档
【发布时间】:2015-06-07 17:18:59
【问题描述】:

我的数据模型大致如下:

data = {
    ...
    parameters: [{type:Schema.Types.mixed}],
    ...
}

如果我现在将一个文档插入到数据库中,

doc = {
  ...
  parameters:[{"foo":"bar"}],
  ...
}

我可以通过“参数”键查询:

db.dataset.find({"parameters":[{"foo":"bar"}]},function(doc){
  ...
})

并取回预期的文档。但是如果“参数”包含多个键,例如

doc = {
  ...
  parameters:[{"foo":"bar","ding":"dong"}]
  ...
}

我再也找不到了。为什么?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这是因为查询无法匹配数组字段parameters 具有精确数组对象作为其值[{"foo": "bar", "ding": "dong"}] 的任何文档。为了证明这一点,让我们在集合中插入几个示例文档:

    /* 0 */
    {
        "_id" : ObjectId("551d777fcfd33f4e2a61e48f"),
        "parameters" : [ 
            {
                "foo" : "bar"
            }
        ]
    }
    
    /* 1 */
    {
        "_id" : ObjectId("551d777fcfd33f4e2a61e490"),
        "parameters" : [ 
            {
                "foo" : "bar",
                "ding" : "dong"
            }
        ]
    }
    

    使用此对象数组[{"foo":"bar"}] 查询此集合中的parameters 数组将得到带有“_id”的文档:ObjectId("551d777fcfd33f4e2a61e48f")。但是,如果您将查询对象更改为使用$elemMatch,那么它将同时带来两个文档:

    db.collection.find({"parameters": { "$elemMatch": { "foo": "bar" } }});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 2014-05-13
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2019-08-12
      相关资源
      最近更新 更多