mongodb/meteor collection check if subdocument field exists when field is a variable

北战南征 提交于 2019-12-25 04:34:31

问题


I'm trying to use something as follows

collection.find({"myField."+variable : {$exists: true})

But obviously that doesn't work because the collections doesn't take strings. Instead, I tried building a a fully query string in JSON but that won't parse correctly because I'm just searching for a field name and not an entire object

var qry = '{"myField.'+variable+'"}'; //no go

I've also tried the meteor collection fields logic

var qry = 'myField.'+variable; 
collection.find({}, {fields: {qry: 1}})

to no avail. I know that a query can take a JSON object but I'm not sure how to write this up.


回答1:


This can be accomplished using bracket notation

var fieldQuery = {};
fieldQuery["myField"+variable] = {$exists: true};

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation




回答2:


Give this a try:

var selector = {};
selector["myField." + variable] = {$exists: true};
Collection.find(selector);


来源:https://stackoverflow.com/questions/31442128/mongodb-meteor-collection-check-if-subdocument-field-exists-when-field-is-a-vari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!