首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pymongo查找有限字符的结果

如何使用pymongo查找有限字符的结果
EN

Stack Overflow用户
提问于 2020-11-25 10:11:33
回答 1查看 25关注 0票数 0

我需要找到postype 2的结果,并按分数从高到低排序。最终结果的正文部分将只显示80个字符(如果少于80个字符,则将显示整个正文)。我对如何将它们组合在一起感到困惑,所以我写了代码的一部分。

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

我的数据看起来是这样的

代码语言:javascript
复制
{
  "_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"
}
EN

回答 1

Stack Overflow用户

发布于 2020-11-26 06:21:32

在示例数据中,PostTypeId是一个字符串,因此必须根据"2" (或'2')而不是2进行过滤。

要修剪这个字段,您可以使用聚合查询和$strlenCP,但是如果您使用的是pymongo,那么只需在python中使用[:80]即可。

示例:

代码语言:javascript
复制
from pymongo import DESCENDING
ret = posts_collection.find({'PostTypeId' : '2'}).sort('Score', DESCENDING)

for record in ret:
    print(record.get('Body', '')[:80])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64997570

复制
相关文章

相似问题

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