Arrays 查询对象与数组
如何查询文档中的对象与对象数组 我需要选择所有类似数据集2的文档 数据集1:Arrays 查询对象与数组,arrays,mongodb,mongodb-query,documents,Arrays,Mongodb,Mongodb Query,Documents,如何查询文档中的对象与对象数组 我需要选择所有类似数据集2的文档 数据集1: { 'firstname' : 'John', 'lastname': 'Smith', 'assistance': [ {'type': 'Food', 'amount': 20} ] } 数据集2: { 'firstname' : 'John', 'lastname': 'Smith', 'assistance': {
{
'firstname' : 'John',
'lastname': 'Smith',
'assistance': [
{'type': 'Food', 'amount': 20}
]
}
数据集2:
{
'firstname' : 'John',
'lastname': 'Smith',
'assistance': {
'type': 'Food',
'amount': 20
}
}
您可以使用$type,因为它不会检查字段是否为数组,它检查的是字段是否包含数组
但如果您正在查找数据集2,则可以对对象使用$type
db.whatever.find( { "assistance" : { $type : 3 } } );
或
MongoDB以BSON格式存储数据 BSON代表二进制JSON BSON支持文档中值的各种数据类型 根据MongoDB的文档 $type选择字段值为 指定BSON类型的实例 根据上述文件 数据集1:协助字段的数据类型为数组 Dataset2:协助字段的数据类型是一个对象 若要仅检索包含数据类型为object的辅助键的文档,请尝试在MongoDB shell中执行以下查询 db.collection.find({assistance:{$type:3}}) 有关BSON类型的更多详细说明,请参阅以下URL中提到的文档 将同时返回文档和
db.foo.find( { "assistance" : { $type : 4 } } ); // 4 is bson type for object
将不返回这两个文档中的任何一个
这是因为在mongodb中,在查询数组时,会在整个数组中检查数组元素
您可以通过以下方式消除辅助类型为array的所有元素:
db.foo.find({"assistance.0" : {$exists : false}})
db.foo.find( { "assistance" : { $type : 4 } } ); // 4 is bson type for object
db.foo.find({"assistance.0" : {$exists : false}})