Как использовать pymongo для поиска результата с ограниченным количеством символов

#python #pymongo

#python #pymongo

Вопрос:

Мне нужно найти результат с помощью 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>nn<p>Currently when I'm in Finder and I try to copy a file to a network share it results in an error:</p>nn<blockquote>n  <p>The Finder can’t complete then  operation because some data in “file_name” can’t be read or written.n  (Error code -36)</p>n</blockquote>nn<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>nn<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"
}
 

Ответ №1:

В вашем примере данные PostTypeId представляют собой строку, поэтому вы должны фильтровать по "2" (или '2' ) и нет 2 .

Чтобы обрезать поле, вы могли бы бороться с агрегированным запросом и $strlenCP , но если вы используете pymongo, просто используйте [:80] в python.

Пример:

 from pymongo import DESCENDING
ret = posts_collection.find({'PostTypeId' : '2'}).sort('Score', DESCENDING)

for record in ret:
    print(record.get('Body', '')[:80])