首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用PyMongo检索数据?

如何使用PyMongo检索数据?
EN

Stack Overflow用户
提问于 2018-12-18 11:30:19
回答 1查看 219关注 0票数 1

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

我已经糊涂了。

首先,我使用PyMODM定义了模式:

代码语言:javascript
复制
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)

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

代码语言:javascript
复制
{
    "position": {
        "x": "1",
        "y": "6"
    },
    "orientation": {
        "x": "0"
    }
}

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

代码语言:javascript
复制
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)

因此,通过只关注路由‘/目标值’的GET方法,如何从我的数据库中检索所有目标消息?

此外,我还想知道,如何在'/ Goal /‘?上检索最后一个目标消息

EN

回答 1

Stack Overflow用户

发布于 2018-12-18 20:06:28

代码语言:javascript
复制
def goals():
    if request.method == 'GET':
        goals = mongo.db.goals.find()
        return jsonify(goals)

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

代码语言:javascript
复制
def goals():
        if request.method == 'GET':
        goals = mongo.db.goals.find().sort({'_id',-1}).limit(1)
        return jsonify(goals)

代码语言:javascript
复制
def goals():
        if request.method == 'GET':
        goals = mongo.db.goals.find().sort({'_id',-1})
        return jsonify(goals)

上面的示例将按降序返回目标集合中所有数据的列表,这意味着最后的更新将位于顶部。

找出

代码语言:javascript
复制
mongo.db.goals.find_one({"_id": ObjectId(id)})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53832070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档