MongoEngine Conditional filter with ReferenceField()Mongoengine ReferenceField Issuemongoengine ListField(ReferenceField()) and custom primary_keymongoengine- what do referencefield storemongoengine - Use QuerySet as ReferenceFieldEmbeddedDocumentField and ReferenceField in mongoengineHow to get ReferenceField data in mongoengine?ReferenceFields with MongoEnginemongoengine referencefield not updatedMongoengine remove ReferenceField valueSetting regex pattern for mongoengine 0.9.0 StringField
Does a 4 bladed prop have almost twice the thrust of a 2 bladed prop?
Based on what criteria do you add/not add icons to labels within a toolbar?
Can chords be inferred from melody alone?
Does a humanoid possessed by a ghost register as undead to a paladin's Divine Sense?
Plato and the knowledge of the forms
Will a research paper be retracted if the code (which was made publically available ) is shown have a flaw in the logic?
Should I take out a personal loan to pay off credit card debt?
Purchased new computer from DELL with pre-installed Ubuntu. Won't boot. Should assume its an error from DELL?
What is it exactly about flying a Flyboard across the English channel that made Zapata's thighs burn?
What prevents ads from reading my password as I type it?
How to realistically deal with a shield user?
Probably terminated or laid off soon; confront or not?
Which genus do I use for neutral expressions in German?
If the interviewer says "We have other interviews to conduct and then back to you in few days", is it a bad sign to not get the job?
Not been paid even after reminding the Treasurer; what should I do?
Why do dragons like shiny stuff?
Can a Hogwarts student refuse the Sorting Hat's decision?
Best way to explain to my boss that I cannot attend a team summit because it is on Rosh Hashana or any other Jewish Holiday
Did silent film actors actually say their lines or did they simply improvise “dialogue” while being filmed?
Non-small objects in categories
Did Apollo leave poop on the moon?
Why does capacitance not depend on the material of the plates?
Changing Row Keys into Normal Rows
How do I get the =LEFT function in excel, to also take the number zero as the first number?
MongoEngine Conditional filter with ReferenceField()
Mongoengine ReferenceField Issuemongoengine ListField(ReferenceField()) and custom primary_keymongoengine- what do referencefield storemongoengine - Use QuerySet as ReferenceFieldEmbeddedDocumentField and ReferenceField in mongoengineHow to get ReferenceField data in mongoengine?ReferenceFields with MongoEnginemongoengine referencefield not updatedMongoengine remove ReferenceField valueSetting regex pattern for mongoengine 0.9.0 StringField
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
Assume that there is simple User
and Post
model.
class User(Document):
user_id = StringField(primary_key=True)
gender = StringField(default='M')
class Post(Document):
user = ReferenceField(User)
body = StringField()
if __name__ == '__main__':
hide = User(user_id='hide', gender='M').save()
john = User(user_id='john', gender='M').save()
test = User(user_id='test', gender='W').save()
admin = User(user_id='admin', gender='W').save()
Post(user=hide, body='hide post').save()
Post(user=john, body='john post').save()
Post(user=test, body='test post').save()
Post(user=admin, body='admin post').save()
hide = User.objects(user_id='hide').first()
posts = Post.objects(user__ne=hide)
for post in posts:
print(post.body)
Result is
john post
test post
admin post
I triggered condition user__ne=hide, So every posts printed except hide's post.
In this case, How can I add more condition likes, gender='W'?
Below code is result of I tried.
posts = Post.objects(user__ne=hide, user__gender__ne='M')
and
from mongoengine.queryset.visitor import Q
posts = Post.objects(Q(user__ne=hide) & Q(user__gender__ne='M'))
But both code throw errors -> mongoengine.errors.InvalidQueryError: Cannot perform join in mongoDB: user__gender
I know it can be implemented with this.
gender = User.objects(gender__ne='M')
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=gender))
But if users has too many rows, it maybe occur memory issue.
Question
Is it possible to querying with condition at once?
Do .objects() actually querying to database?
mongodb mongoengine
add a comment |
Assume that there is simple User
and Post
model.
class User(Document):
user_id = StringField(primary_key=True)
gender = StringField(default='M')
class Post(Document):
user = ReferenceField(User)
body = StringField()
if __name__ == '__main__':
hide = User(user_id='hide', gender='M').save()
john = User(user_id='john', gender='M').save()
test = User(user_id='test', gender='W').save()
admin = User(user_id='admin', gender='W').save()
Post(user=hide, body='hide post').save()
Post(user=john, body='john post').save()
Post(user=test, body='test post').save()
Post(user=admin, body='admin post').save()
hide = User.objects(user_id='hide').first()
posts = Post.objects(user__ne=hide)
for post in posts:
print(post.body)
Result is
john post
test post
admin post
I triggered condition user__ne=hide, So every posts printed except hide's post.
In this case, How can I add more condition likes, gender='W'?
Below code is result of I tried.
posts = Post.objects(user__ne=hide, user__gender__ne='M')
and
from mongoengine.queryset.visitor import Q
posts = Post.objects(Q(user__ne=hide) & Q(user__gender__ne='M'))
But both code throw errors -> mongoengine.errors.InvalidQueryError: Cannot perform join in mongoDB: user__gender
I know it can be implemented with this.
gender = User.objects(gender__ne='M')
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=gender))
But if users has too many rows, it maybe occur memory issue.
Question
Is it possible to querying with condition at once?
Do .objects() actually querying to database?
mongodb mongoengine
add a comment |
Assume that there is simple User
and Post
model.
class User(Document):
user_id = StringField(primary_key=True)
gender = StringField(default='M')
class Post(Document):
user = ReferenceField(User)
body = StringField()
if __name__ == '__main__':
hide = User(user_id='hide', gender='M').save()
john = User(user_id='john', gender='M').save()
test = User(user_id='test', gender='W').save()
admin = User(user_id='admin', gender='W').save()
Post(user=hide, body='hide post').save()
Post(user=john, body='john post').save()
Post(user=test, body='test post').save()
Post(user=admin, body='admin post').save()
hide = User.objects(user_id='hide').first()
posts = Post.objects(user__ne=hide)
for post in posts:
print(post.body)
Result is
john post
test post
admin post
I triggered condition user__ne=hide, So every posts printed except hide's post.
In this case, How can I add more condition likes, gender='W'?
Below code is result of I tried.
posts = Post.objects(user__ne=hide, user__gender__ne='M')
and
from mongoengine.queryset.visitor import Q
posts = Post.objects(Q(user__ne=hide) & Q(user__gender__ne='M'))
But both code throw errors -> mongoengine.errors.InvalidQueryError: Cannot perform join in mongoDB: user__gender
I know it can be implemented with this.
gender = User.objects(gender__ne='M')
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=gender))
But if users has too many rows, it maybe occur memory issue.
Question
Is it possible to querying with condition at once?
Do .objects() actually querying to database?
mongodb mongoengine
Assume that there is simple User
and Post
model.
class User(Document):
user_id = StringField(primary_key=True)
gender = StringField(default='M')
class Post(Document):
user = ReferenceField(User)
body = StringField()
if __name__ == '__main__':
hide = User(user_id='hide', gender='M').save()
john = User(user_id='john', gender='M').save()
test = User(user_id='test', gender='W').save()
admin = User(user_id='admin', gender='W').save()
Post(user=hide, body='hide post').save()
Post(user=john, body='john post').save()
Post(user=test, body='test post').save()
Post(user=admin, body='admin post').save()
hide = User.objects(user_id='hide').first()
posts = Post.objects(user__ne=hide)
for post in posts:
print(post.body)
Result is
john post
test post
admin post
I triggered condition user__ne=hide, So every posts printed except hide's post.
In this case, How can I add more condition likes, gender='W'?
Below code is result of I tried.
posts = Post.objects(user__ne=hide, user__gender__ne='M')
and
from mongoengine.queryset.visitor import Q
posts = Post.objects(Q(user__ne=hide) & Q(user__gender__ne='M'))
But both code throw errors -> mongoengine.errors.InvalidQueryError: Cannot perform join in mongoDB: user__gender
I know it can be implemented with this.
gender = User.objects(gender__ne='M')
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=gender))
But if users has too many rows, it maybe occur memory issue.
Question
Is it possible to querying with condition at once?
Do .objects() actually querying to database?
mongodb mongoengine
mongodb mongoengine
asked Mar 27 at 3:35
HideHide
6251 gold badge5 silver badges25 bronze badges
6251 gold badge5 silver badges25 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
As detailed on the sibling github ticket
1 - There is no joins in mongodb so there is no other option than the one you suggested. One simple thing you can do to improve performance and reduce the memory footprint is to fetch only the user ids, see below:
male_ids = User.objects(gender__ne='M').scalar('id') # Only fetch the user ids, i.o loading full object data into User model
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=male_ids))
Note: There is a CachedReferenceField in mongoengine that might help you to achieve what you want (it would basically duplicates the value of gender
next to the reference to the user in the Post collection) and keep it in sync but CachedReferenceField suffers from some bugs (and performance issue to keep them in sync) so maybe it could do the trick for simple use cases but I wouldn't advise to use it.
2 - .objects()
returns a queryset, the query is only fired when you iterate over the queryset (or print the queryset). See below:
user_qs = User.objects()
print(type(user_qs)) # <class mongoengine.queryset.queryset.QuerySet>, query not fired yet
for user in qs_user: # fires the actual query and load data in User instances
pass
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55369396%2fmongoengine-conditional-filter-with-referencefield%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
As detailed on the sibling github ticket
1 - There is no joins in mongodb so there is no other option than the one you suggested. One simple thing you can do to improve performance and reduce the memory footprint is to fetch only the user ids, see below:
male_ids = User.objects(gender__ne='M').scalar('id') # Only fetch the user ids, i.o loading full object data into User model
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=male_ids))
Note: There is a CachedReferenceField in mongoengine that might help you to achieve what you want (it would basically duplicates the value of gender
next to the reference to the user in the Post collection) and keep it in sync but CachedReferenceField suffers from some bugs (and performance issue to keep them in sync) so maybe it could do the trick for simple use cases but I wouldn't advise to use it.
2 - .objects()
returns a queryset, the query is only fired when you iterate over the queryset (or print the queryset). See below:
user_qs = User.objects()
print(type(user_qs)) # <class mongoengine.queryset.queryset.QuerySet>, query not fired yet
for user in qs_user: # fires the actual query and load data in User instances
pass
add a comment |
As detailed on the sibling github ticket
1 - There is no joins in mongodb so there is no other option than the one you suggested. One simple thing you can do to improve performance and reduce the memory footprint is to fetch only the user ids, see below:
male_ids = User.objects(gender__ne='M').scalar('id') # Only fetch the user ids, i.o loading full object data into User model
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=male_ids))
Note: There is a CachedReferenceField in mongoengine that might help you to achieve what you want (it would basically duplicates the value of gender
next to the reference to the user in the Post collection) and keep it in sync but CachedReferenceField suffers from some bugs (and performance issue to keep them in sync) so maybe it could do the trick for simple use cases but I wouldn't advise to use it.
2 - .objects()
returns a queryset, the query is only fired when you iterate over the queryset (or print the queryset). See below:
user_qs = User.objects()
print(type(user_qs)) # <class mongoengine.queryset.queryset.QuerySet>, query not fired yet
for user in qs_user: # fires the actual query and load data in User instances
pass
add a comment |
As detailed on the sibling github ticket
1 - There is no joins in mongodb so there is no other option than the one you suggested. One simple thing you can do to improve performance and reduce the memory footprint is to fetch only the user ids, see below:
male_ids = User.objects(gender__ne='M').scalar('id') # Only fetch the user ids, i.o loading full object data into User model
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=male_ids))
Note: There is a CachedReferenceField in mongoengine that might help you to achieve what you want (it would basically duplicates the value of gender
next to the reference to the user in the Post collection) and keep it in sync but CachedReferenceField suffers from some bugs (and performance issue to keep them in sync) so maybe it could do the trick for simple use cases but I wouldn't advise to use it.
2 - .objects()
returns a queryset, the query is only fired when you iterate over the queryset (or print the queryset). See below:
user_qs = User.objects()
print(type(user_qs)) # <class mongoengine.queryset.queryset.QuerySet>, query not fired yet
for user in qs_user: # fires the actual query and load data in User instances
pass
As detailed on the sibling github ticket
1 - There is no joins in mongodb so there is no other option than the one you suggested. One simple thing you can do to improve performance and reduce the memory footprint is to fetch only the user ids, see below:
male_ids = User.objects(gender__ne='M').scalar('id') # Only fetch the user ids, i.o loading full object data into User model
posts = Post.objects(Q(user__ne=hide) & Q(user__nin=male_ids))
Note: There is a CachedReferenceField in mongoengine that might help you to achieve what you want (it would basically duplicates the value of gender
next to the reference to the user in the Post collection) and keep it in sync but CachedReferenceField suffers from some bugs (and performance issue to keep them in sync) so maybe it could do the trick for simple use cases but I wouldn't advise to use it.
2 - .objects()
returns a queryset, the query is only fired when you iterate over the queryset (or print the queryset). See below:
user_qs = User.objects()
print(type(user_qs)) # <class mongoengine.queryset.queryset.QuerySet>, query not fired yet
for user in qs_user: # fires the actual query and load data in User instances
pass
edited Jun 5 at 9:05
answered Jun 4 at 19:14
bagerardbagerard
7855 silver badges13 bronze badges
7855 silver badges13 bronze badges
add a comment |
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55369396%2fmongoengine-conditional-filter-with-referencefield%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown