我需要找到postype 2的结果,并按分数从高到低排序。最终结果的正文部分将只显示80个字符(如果少于80个字符,则将显示整个正文)。我对如何将它们组合在一起感到困惑,所以我写了代码的一部分。
climit = {"$redact":{"$cond":[{"$gt":[{"strlenCP":"$name"},80]},"$$KEEP","$$PRUNE"]}}
ctype = {"$match":{"PostTypeId" : 2}}
search = [ctype,climit]
ret = posts_collection.find(ctype)
for i in ret:
print(i)我的数据看起来是这样的
{
"_id" : ObjectId("5fbcf481fc6360b2e1922476"),
"Id" : "99",
"PostTypeId" : "1",
"AcceptedAnswerId" : "103",
"CreationDate" : "2010-08-17T20:31:26.913",
"Score" : 9,
"ViewCount" : 5880,
"Body" : "<p>Is there a way to tell Finder to not use (or worry about) the ._* files and other meta-data files it normally tries to use when it's on a network share?</p>\n\n<p>Currently when I'm in Finder and I try to copy a file to a network share it results in an error:</p>\n\n<blockquote>\n <p>The Finder can’t complete the\n operation because some data in “file_name” can’t be read or written.\n (Error code -36)</p>\n</blockquote>\n\n<p>But I can copy the file from the terminal command line to the network share and use it from Finder afterward just fine. It seems that the meta-data isn't really needed on the network share. Is there a way to tell Finder this?</p>\n\n<p>For reference, I'm using Snow Leopard and the share is a Samba share on a Linux server.</p>\n",
"OwnerUserId" : "41",
"LastActivityDate" : "2018-11-21T01:21:42.893",
"Title" : "Dot-files and other meta data on non-Mac network shares",
"Tags" : "<finder><samba>",
"AnswerCount" : 4,
"CommentCount" : 1,
"FavoriteCount" : 4,
"ContentLicense" : "CC BY-SA 2.5"
}发布于 2020-11-26 06:21:32
在示例数据中,PostTypeId是一个字符串,因此必须根据"2" (或'2')而不是2进行过滤。
要修剪这个字段,您可以使用聚合查询和$strlenCP,但是如果您使用的是pymongo,那么只需在python中使用[:80]即可。
示例:
from pymongo import DESCENDING
ret = posts_collection.find({'PostTypeId' : '2'}).sort('Score', DESCENDING)
for record in ret:
print(record.get('Body', '')[:80])https://stackoverflow.com/questions/64997570
复制相似问题