【问题标题】:How can I retrieve data using PyMongo?如何使用 PyMongo 检索数据?
【发布时间】:2018-12-18 11:30:19
【问题描述】:

我已经阅读了教程,因为我使用了三个不同的东西: 1. Flask 作为服务器 2. PyMongo 作为 MongoDB 驱动程序 3. PyMODM 作为模式创建者

我已经糊涂了。

首先,我使用 PyMODM 定义了 Schema:

from pymongo import TEXT
from pymongo.operations import IndexModel
from pymodm import connect, fields, MongoModel, EmbeddedMongoModel

class GoalPosition(EmbeddedMongoModel):
    x = fields.IntegerField()
    y = fields.IntegerField()

class GoalOrientation(EmbeddedMongoModel):
    x = fields.IntegerField()

class Goal(EmbeddedMongoModel):
    position = fields.EmbeddedDocumentField(GoalPosition)
    orientation = fields.EmbeddedDocumentField(GoalOrientation)

class Path(MongoModel):
    path = fields.EmbeddedDocumentListField(Goal)

从上面,我的想法是制作两种类型的模式:目标和路径。最后,目标看起来像这样:

{
    "position": {
        "x": "1",
        "y": "6"
    },
    "orientation": {
        "x": "0"
    }
}

Path 将是一个目标列表。 有了我的模式,最大的问题是,我如何使用它与我的 MongoDB 数据库进行通信?这是我的小型服务器代码:

from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from flask_pymongo import PyMongo
from flask import jsonify


app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb+srv://user:pass@cluster0-qhfvu.mongodb.net/test?retryWrites=true"
mongo = PyMongo(app)

@app.route('/goal', methods=['GET', 'POST'])
def goals():
    if request.method == 'GET':
        goals = mongo.db.goals.find()
        return jsonify(goals)

    elif request.method == 'POST':
        position = request.body.position
        orientation = request.body.orientation
        print position
        flash("Goal added")

@app.route('/goal/<id>')
def goal(id):
    goal = mongo.db.goals.find_one_or_404({"_id" : id})
    return jsonify(goal)

因此,通过只关注路径“/goal”的 GET 方法,我如何从我的数据库中检索所有 Goal 消息?

另外,我想知道如何在 '/goal/' 检索最后一条目标消息?

【问题讨论】:

  • 我不明白你的问题。你已经在这样做了。你哪里出了问题?
  • @DanielRoseman 你是说我的代码是正确的吗?但是flask server和pymongo怎么知道“mongo.db.goals.find()”是什么?

标签: python pymongo pymodm


【解决方案1】:
def goals():
    if request.method == 'GET':
        goals = mongo.db.goals.find()
        return jsonify(goals)

您已经在检索目标集合中的所有记录。下面的示例将为您提供一条最新的记录。

def goals():
        if request.method == 'GET':
        goals = mongo.db.goals.find().sort({'_id',-1}).limit(1)
        return jsonify(goals)

.

def goals():
        if request.method == 'GET':
        goals = mongo.db.goals.find().sort({'_id',-1})
        return jsonify(goals)

以上示例将按降序返回目标集合中所有数据的列表,这意味着最后更新将在最前面

寻找

mongo.db.goals.find_one({"_id": ObjectId(id)})

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 2019-11-24
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多