У меня есть две коллекции mongodb. первый books collection
, а второй user collection
. я присоединился к этим двум коллекциям, используя метод $lookup
.
коллекция пользователей
{"_id":{"$oid":"5e463237c74759a880443a78"},
"name":"vatsalay khobragade",
"email":"vatsalayvk1434@gmail.com",
"password":{"$binary{"base64":"JDJiJDEyJDl6WGlRVWNnWWdIWFFXYzIzeEQ4MWVKVnpsUzNWNWI5SkpmMGxab1k0TDRlakVIeDl1LjdD","subType":"00"}},
"address":"rajnandgaon",
"location":{"type":"Point","coordinates":[{"$numberDouble":"20.9727404"},{"$numberDouble":"80.69155548263583"}]},
"fulladdress":"Rajnandgaon, Chhattisgarh, India",
"isVerified":true,
"facebook":null,
"instagram":null
},
{"_id":{"$oid":"5e5d35825738ca47fbf99484"},
"name":"vatsalay k",
"email":"vatsalaykhobragade1234@gmail.com",
"password":{"$binary":{"base64":"JDJiJDEyJFpKTTU4bTVtOHBxTW5YRm1GU1hwWU8wenAuWVUuUGg0U2wyT044MFFweFUzc01oY2Mzckwy",
"subType":"00"}},
"address":"bhilai",
"location":{"type":"Point","coordinates":[{"$numberDouble":"21.2120677"},{"$numberDouble":"81.3732849"}]},
"fulladdress":"Bhilai, Durg Tahsil, Durg, Chhattisgarh, 490036, India",
"isVerified":true,
"donateList":[[{"bookid":{"$oid":"5e5d365b5738ca47fbf99485"}}]]
}
коллекция книг
{"_id":{"$oid":"5e2af0e82b9a4157f000cad8"},
"bookname":"javascript book",
"bookdesc":"its a javascript book","donatedby":"vatsalay khobragade"
},
{"_id":{"$oid":"5e315dc9a92ad961795d9718"},
"bookname":"python 3 book",
"bookdesc":"armin rochnaher",
"donatedby":"vatsalay khobragade"
}
объединенные коллекции
{'_id': ObjectId('5e463237c74759a880443a78'),
'name': 'vatsalay khobragade',
'email': 'vatsalayvk1434@gmail.com',
'password': b'$2b$12$9zXiQUcgYgHXQWc23xD81eJVzlS3V5b9JJf0lZoY4L4ejEHx9u.7C', 'address': 'rajnandgaon',
'location': {'type': 'Point', 'coordinates': [20.9727404, 80.69155548263583]},
'fulladdress': 'Rajnandgaon, Chhattisgarh, India', 'isVerified': True, 'facebook': None,
'instagram': None,
'books': [{'_id': ObjectId('5e2af0e82b9a4157f000cad8'), 'bookname': 'javascript book', 'bookdesc': 'its a javascript book', 'donatedby': 'vatsalay khobragade'},
{'_id': ObjectId('5e314eed3f84e7cf7f0a5bfe'),
'bookname': 'biology book', 'bookdesc': 'its a biology book\r\n', 'donatedby': 'vatsalay khobragade'},
{'_id': ObjectId('5e315dc9a92ad961795d9718'), 'bookname': 'python 3 book', 'bookdesc': 'armin rochnaher', 'donatedby': 'vatsalay khobragade'}]
}
Теперь вот мой вариант использования: у меня есть форма поиска, где пользователи могут искать книги. поэтому, если пользователь ищет книгу, например: javascript book и если у меня есть эта javascript book в этой объединенной коллекции, то я хочу показать три информации: bookname
, book description
и donated by
. По сути, я заинтересован в массиве книги . сейчас я не могу этого сделать. я не знаю, смогу ли я использовать findOne method
или что-нибудь подобное для этого. сейчас он дает мне все book names
, book descriptions
и donated by
даже без поиска, чего я не хочу.
Flask Код
@app.route('/request books', methods=['GET', 'POST'])
@app.route('/get books', methods=['GET', 'POST'])
def requesting_for_books():
try:
mydb = mongo.db.mylogin
user_col = mydb.find_one({"email" : session['email']})
final = dict(user_col)
verify = final['isVerified']
form = RequestBooks()
if ('email' in session and verify == True) and ('password' in session and request.method == 'GET'):
return render_template('get_books.html', title="Get Books", donated_by=session['username'], form=form)
elif 'email' in session and request.method == 'POST':
requesting = mongo.db.mylogin
# Requesting_books = requesting.find_one({'bookname': request.form['bookname']})
#createing index
mongo.db.mylogin.create_index([("location", pymongo.GEOSPHERE )])
request_books = requesting.find({ "location": { "$nearSphere": { "$geometry" : {"type" : "Point", "coordinates": [session['lang'], session['lat']]}, "$minDistance": 0, "$maxDistance" : 5000 } } })
getting_book = requesting.aggregate([{"$lookup" : {"from" : "books", "localField" : "name", "foreignField" : "donatedby", "as" : "books"}}])
x = []
for i in getting_book:
x.append(i)
real_data = x
for j in real_data:
data = j['books']
# for books in data:
# exact = books
if request_books == None:
flash("Please enter a search query !")
return render_template('get_books.html', title='Get Books', form=form)
else:
return render_template('get_books.html', title="Get Books", x=x, request_books=request_books, real_data=real_data, data=data, form=form)
else:
flash('Please Login/Sign Up first to Search for books !')
return redirect(url_for('home'))
except KeyError:
flash("Please Sign in first !")
return render_template('index.html', title="Home")
Мой шаблон
{% if x %}
{% for books in data %}
<div class="container">
<div class="row">
<div class="col-sm">
<div class="card mt-5 mb-3 ml-4 pb-5">
<div class="container pb-5">
<div class="mt-1">
<p id="my-text" class="font-weight-bold" style="font-size: 17px; margin-bottom: 0.5rem;">{{books['bookname']}}
</p>
<p class="font-weight-light" style="font-size: 15px; margin-bottom: 0.5rem;">{{books['bookdesc']}}
</p>
<i class="fas fa-hand-holding-usd" style="float: left;"></i>
<p id="my-text" style="font-size: 15px;" class="pl-4">{{books['donatedby']}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% endif %}