MongoDB:查询名称中带有空格的键 [英] MongoDB: Query a key having space in its name

查看:581
本文介绍了MongoDB:查询名称中带有空格的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想从MongoDB集合中检索某些键的值.

I want to retrieve values of only certain keys from a MongoDB collection.

但是,集合中有一些键的名称带有空格",例如:

But, the collection has some keys which have a 'space' in their name like:

"Parent":{"key1": //some string,
          "key2": //some string,
          "key 3": //some string}

我知道这是一种错误的方法,因为理想情况下,键名中不应包含空格,但是如何查询此键?我正在使用Python和PyMongo.

I know this is a wrong approach as there shouldn't ideally be spaces in a key name but nevertheless how do I query this key? I am using Python and PyMongo.

对于普通键,我可以这样做:

For normal keys I can do this:

db.coll_name.find({"key": "India"}, {"_id": 0, "Parent.key1": 1, "Parent.key2": 1})

那么如何在上述查询的第二个参数中使用键"Parent ['key 3']"?有什么办法可以做到这一点?

So how do I use the key "Parent['key 3']" in the second argument of the above query? Is there any way to achieve this?

以下是返回数据(有效)的查询:

db.coll_name.find({}, {"Parent.key1": 1, "_id": 0})

以下是不返回数据的查询:

db.coll_name.find({}, {"Parent['key 3']": 1, "_id": 0})

推荐答案

构造此方法的唯一方法是:

Well the only way you could have constructed this is like:

content = {};
content["Parent"] = {}
content["Parent"]["key2"] = 1
content["Parent"]["key 3"] = 1

db.coll_name.insert(content)

但是您似乎想念这样做没有错:

But you seem to be missing that there is nothing wrong with doing this:

db.coll_name.find({ "Parent.key 3":  1} )

或处于投影状态

 db.coll_name.find({}, { "Parent.key 3": 1 })

它是点符号" ,而不是对象符号,并且只要您引用键名(点符号是必需的),就可以了,并且可以在其中留一个空格.

It's "dot notation" and not object notation, and as long as you quote the key names ( which is mandatory for dot notation ) then all it fine and you can have a space in there.

这篇关于MongoDB:查询名称中带有空格的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆