kandi background
Explore Kits

mongoengine | A Python Object-Document-Mapper for working with MongoDB | SQL Database library

 by   MongoEngine Python Version: v0.24.0 License: MIT

 by   MongoEngine Python Version: v0.24.0 License: MIT

Download this library from

kandi X-RAY | mongoengine Summary

mongoengine is a Python library typically used in Database, SQL Database, MongoDB applications. mongoengine has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub.
A Python Object-Document-Mapper for working with MongoDB
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • mongoengine has a highly active ecosystem.
  • It has 3686 star(s) with 1179 fork(s). There are 133 watchers for this library.
  • There were 1 major release(s) in the last 12 months.
  • There are 335 open issues and 1245 have been closed. On average issues are closed in 161 days. There are 38 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of mongoengine is v0.24.0
mongoengine Support
Best in #SQL Database
Average in #SQL Database
mongoengine Support
Best in #SQL Database
Average in #SQL Database

quality kandi Quality

  • mongoengine has 0 bugs and 0 code smells.
mongoengine Quality
Best in #SQL Database
Average in #SQL Database
mongoengine Quality
Best in #SQL Database
Average in #SQL Database

securitySecurity

  • mongoengine has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • mongoengine code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
mongoengine Security
Best in #SQL Database
Average in #SQL Database
mongoengine Security
Best in #SQL Database
Average in #SQL Database

license License

  • mongoengine is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
mongoengine License
Best in #SQL Database
Average in #SQL Database
mongoengine License
Best in #SQL Database
Average in #SQL Database

buildReuse

  • mongoengine releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • mongoengine saves you 12755 person hours of effort in developing the same functionality from scratch.
  • It has 26256 lines of code, 1828 functions and 88 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
mongoengine Reuse
Best in #SQL Database
Average in #SQL Database
mongoengine Reuse
Best in #SQL Database
Average in #SQL Database
Top functions reviewed by kandi - BETA

kandi has reviewed mongoengine and discovered the below as its top functions. This is intended to give you an instant insight into mongoengine implemented functionality, and help decide if they suit your requirements.

  • Creates a new instance of this class .
  • Gets mongo query .
  • Save document .
  • Lookup a field from a list of fields .
  • Gets connection settings .
  • Perform a map reduce operation .
  • Attaches the specified objects to a list .
  • Initializes this class .
  • Puts an image into a file .
  • Returns the connection associated with the given alias .

mongoengine Key Features

A Python Object-Document-Mapper for working with MongoDB

Mongo: document from ReferenceField was deleted - how to handle DoesNotExist gracefully?

copy iconCopydownload iconDownload
class Event(Document):
    type = StringField(required=True)
    party= ReferenceField(
        Party, required=True,
        reverse_delete_rule=mongoengine.PULL
    )

Query by computed property in python mongoengine

copy iconCopydownload iconDownload
from mongoengine import Document, ReferenceField

class Snapshot(Document)
property_abc = RelevantPropertyHere() # anything you need

class SnapshotIndicatorKeyValue(Document):
snapshot = ReferenceField(Snapshot)
sample_snapshot = Snapshot(property_abc=relevant_value_here) # anything you need
sample_snapshot.save()

sample_indicatorkeyvalue = SnapshotIndicatorKeyValue()
sample_indicatorkeyvalue.snapshot = sample_snapshot
sample_indicatorkeyvalue.save()
SnapshotIndicatorKeyValue.objects.first().snapshot.property_abc
-----------------------
from mongoengine import Document, ReferenceField

class Snapshot(Document)
property_abc = RelevantPropertyHere() # anything you need

class SnapshotIndicatorKeyValue(Document):
snapshot = ReferenceField(Snapshot)
sample_snapshot = Snapshot(property_abc=relevant_value_here) # anything you need
sample_snapshot.save()

sample_indicatorkeyvalue = SnapshotIndicatorKeyValue()
sample_indicatorkeyvalue.snapshot = sample_snapshot
sample_indicatorkeyvalue.save()
SnapshotIndicatorKeyValue.objects.first().snapshot.property_abc
-----------------------
from mongoengine import Document, ReferenceField

class Snapshot(Document)
property_abc = RelevantPropertyHere() # anything you need

class SnapshotIndicatorKeyValue(Document):
snapshot = ReferenceField(Snapshot)
sample_snapshot = Snapshot(property_abc=relevant_value_here) # anything you need
sample_snapshot.save()

sample_indicatorkeyvalue = SnapshotIndicatorKeyValue()
sample_indicatorkeyvalue.snapshot = sample_snapshot
sample_indicatorkeyvalue.save()
SnapshotIndicatorKeyValue.objects.first().snapshot.property_abc

Aggregation function for Counting of Duplicates in a field based on duplicate items in another field

copy iconCopydownload iconDownload
db.collection.aggregate([
{
  "$group": {
  "_id": {
    k: "$organization",
    v: "$val"
   },
  "cnt": {
    $sum: 1
   }
  }
 },
 {
  $project: {
    _id: 0,
    k: "$_id.k",
    o: {
      k: "$_id.v",
      v: "$cnt"
    }
   }
  },
 {
   $group: {
    _id: "$k",
    v: {
      $push: "$o"
    }
  }
},
{
  $addFields: {
    v: {
      "$arrayToObject": "$v"
    }
  }
},
{
  $project: {
    _id: 0,
    new: [
      {
        k: "$_id",
        v: "$v"
      }
    ]
  }
},
{
  "$addFields": {
    "new": {
      "$arrayToObject": "$new"
    }
  }
},
{
 "$replaceRoot": {
   "newRoot": "$new"
 }
}
])
   {
   $addFields: {
     v: {
    "$mergeObjects": [
      {
        "null": 0,
        valid: 0,
        invalid: 0
      },
      {
        "$arrayToObject": "$v"
      }
    ]
   }
  }
 }
-----------------------
db.collection.aggregate([
{
  "$group": {
  "_id": {
    k: "$organization",
    v: "$val"
   },
  "cnt": {
    $sum: 1
   }
  }
 },
 {
  $project: {
    _id: 0,
    k: "$_id.k",
    o: {
      k: "$_id.v",
      v: "$cnt"
    }
   }
  },
 {
   $group: {
    _id: "$k",
    v: {
      $push: "$o"
    }
  }
},
{
  $addFields: {
    v: {
      "$arrayToObject": "$v"
    }
  }
},
{
  $project: {
    _id: 0,
    new: [
      {
        k: "$_id",
        v: "$v"
      }
    ]
  }
},
{
  "$addFields": {
    "new": {
      "$arrayToObject": "$new"
    }
  }
},
{
 "$replaceRoot": {
   "newRoot": "$new"
 }
}
])
   {
   $addFields: {
     v: {
    "$mergeObjects": [
      {
        "null": 0,
        valid: 0,
        invalid: 0
      },
      {
        "$arrayToObject": "$v"
      }
    ]
   }
  }
 }

Modifying DictField in multiple documents together stored in Mongodb using mongoengine

copy iconCopydownload iconDownload
db.collection.update({
   "ml_proc": {
     $exists: false
  }
 },
 [
  {
    $addFields: {
      ml_proc: {
        sm: {
          $sum: [
            "$num1",
            2
          ]
        },
        prod: {
          $sum: [
            "$num2",
            2
          ]
        }
       }
      }
    }
 ],
 {
  multi: true
})

FastAPI refuses to let me create a mongoengine document

copy iconCopydownload iconDownload
class Accounts(Document):
    meta = {'db_alias': 'some_db',
            'collection': 'things'}

How to override mongoengine's QuerySet method?

copy iconCopydownload iconDownload
class TransactionQuerySet(QuerySet):

    def order_by(self, *args, target_data=None):
        if target_data is None:
            return super().order_by(*args)
        return "transactions sorted by target data"
class Transaction(Document):
    title = StringField(max_length=100, required=True)
    last_modified = DateTimeField(default=datetime.utcnow)
    
    def __str__(self):
        return self.title

    meta = {"collection": "transaction_collection"}


with MongoClient("mongodb://localhost:27017") as client:
    connection = client.get_database("transaction")
    collection = connection.transaction_collection
    transaction_set = TransactionQuerySet(Transaction, collection)

    print(transaction_set.order_by("-title"))
[<Transaction: ETHUSTD>, <Transaction: BTCUSTD>, ...]
-----------------------
class TransactionQuerySet(QuerySet):

    def order_by(self, *args, target_data=None):
        if target_data is None:
            return super().order_by(*args)
        return "transactions sorted by target data"
class Transaction(Document):
    title = StringField(max_length=100, required=True)
    last_modified = DateTimeField(default=datetime.utcnow)
    
    def __str__(self):
        return self.title

    meta = {"collection": "transaction_collection"}


with MongoClient("mongodb://localhost:27017") as client:
    connection = client.get_database("transaction")
    collection = connection.transaction_collection
    transaction_set = TransactionQuerySet(Transaction, collection)

    print(transaction_set.order_by("-title"))
[<Transaction: ETHUSTD>, <Transaction: BTCUSTD>, ...]
-----------------------
class TransactionQuerySet(QuerySet):

    def order_by(self, *args, target_data=None):
        if target_data is None:
            return super().order_by(*args)
        return "transactions sorted by target data"
class Transaction(Document):
    title = StringField(max_length=100, required=True)
    last_modified = DateTimeField(default=datetime.utcnow)
    
    def __str__(self):
        return self.title

    meta = {"collection": "transaction_collection"}


with MongoClient("mongodb://localhost:27017") as client:
    connection = client.get_database("transaction")
    collection = connection.transaction_collection
    transaction_set = TransactionQuerySet(Transaction, collection)

    print(transaction_set.order_by("-title"))
[<Transaction: ETHUSTD>, <Transaction: BTCUSTD>, ...]

How to handle possible race-condition in overwritten Document.save method - Mongoengine

copy iconCopydownload iconDownload
    assert self.group is not None
    assert self.user is not None

Trying to test Flask endpoint. AttributeError: 'PosixPath' object has no attribute 'lstrip'

copy iconCopydownload iconDownload
APPLICATION_ROOT = Path(__file__).parent.parent

HaltServer 'App failed to load.' when deploying to google cloud

copy iconCopydownload iconDownload
gunicorn
gunicorn==20.0.4
-----------------------
gunicorn
gunicorn==20.0.4

How to calculate the amount with conditional?

copy iconCopydownload iconDownload
query = {
    'createdTimestamp': {'$gte': 1632430800, '$lte': 1632517200},
}
pipeline = [
    {"$match": query},
    {
        "$group": {
            "_id": None,
            "total_amount": {
                "$sum": {
                    "$cond": [
                        {
                            "$gt": [
                                "$amountOut",
                                0
                            ]
                        },
                        "$amountOut",
                        "$amountIn"
                    ]
                }
            }
        }
    }
]

records = db.RecordModel.objects().aggregate(pipeline)

Community Discussions

Trending Discussions on mongoengine
  • Mongo: document from ReferenceField was deleted - how to handle DoesNotExist gracefully?
  • Query by computed property in python mongoengine
  • Aggregation function for Counting of Duplicates in a field based on duplicate items in another field
  • Modifying DictField in multiple documents together stored in Mongodb using mongoengine
  • How to convert Python mongongine object (Document) to dictionary?
  • FastAPI refuses to let me create a mongoengine document
  • Error while downloading the requirements using pip install (setup command: use_2to3 is invalid.)
  • How to override mongoengine's QuerySet method?
  • How to handle possible race-condition in overwritten Document.save method - Mongoengine
  • dynamic collection name using python mongoengine
Trending Discussions on mongoengine

QUESTION

Mongo: document from ReferenceField was deleted - how to handle DoesNotExist gracefully?

Asked 2022-Apr-01 at 16:29

Say I have a model like this one:

class Event(Document):
    type = StringField(required=True)
    party= ReferenceField(Party, required=True, null=False)

that I save instances of like this:

some_party = Party.objects.first()

Event(
    type='some event type',
    party=some_party,
).save() 

Now if at some point in time I do some_party.delete() and try to to retrieve any event that has a reference to some_party in its "party" field, I will get an error like this one:

mongoengine.errors.DoesNotExist: Trying to dereference unknown document DBRef('party', ObjectId('62286f65088c4f1d723574c6'))

What would be a neat way to handle such situations? Should I leave it like this and maybe pepper my code with try/except blocks to check for DoesNotExist, or should I maybe somehow convert missing reference to None, etc.?

ANSWER

Answered 2022-Apr-01 at 16:29

With mongoengine, the ReferenceField's reverse_delete_rule property can address situations where a document deletion leads to consistency issues.

The reverse_delete_rule's mongoengine.NULLIFY attribute turns the fields referring to the deleted object to None. This requires to drop the null=False declaration.

Your Event class would be amended like this:

class Event(Document):
    type = StringField(required=True)
    party= ReferenceField(
        Party, required=True,
        reverse_delete_rule=mongoengine.PULL
    )

You have two alternatives, depending on your design choices:

  • mongoengine.DENY would prevent the deletion of the referenced object
  • mongoengine.CASCADE would delete the documents associated with the referenced object as well as the referenced object.

The full list of attributes can be found in this section of mongoengine's documentation.

Source https://stackoverflow.com/questions/71466636

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install mongoengine

You can download it from GitHub.
You can use mongoengine like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Consider Popular SQL Database Libraries
Compare SQL Database Libraries with Highest Support
Compare SQL Database Libraries with Highest Quality
Compare SQL Database Libraries with Highest Security
Compare SQL Database Libraries with Permissive License
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.