gpt4 book ai didi

mongodb - 如何使用 Powershell 对 MongoDB 进行复杂查询

转载 作者:可可西里 更新时间:2023-11-01 09:54:57 27 4
gpt4 key购买 nike

我需要使用 Powershell 从 mongoDB 检索数据。假设我有 db.orders 集合,只需要检索上周创建的订单,并且只检索特定列,例如 _id、status、createdAt 字段。

订单集合架构

{
"_id": ObjectId("56cf9bab78e9fd46ec557d69"),
"status" : "ordered",
...
"total": 343,
"createdAt": ISODate("2016-01-15T17:29:09.342Z")
}

我可以像这样在 mongo shell 中查询它

db.orders.find({ 
"createdAt" : {
$lt: new Date(),
$gte: new Date(new Date().setDate(new Date().getDate()-7))
}
}, {_id: 1, status: 1, createdAt: 1 })

但我需要在 Powershell 中执行此操作,这是我的 Powershell 脚本,其中包含简单的查询,它准确地提取了 createdAt date.. 而不是日期范围

$mongoDbDriverPath = "C:\mongodb\bin"
$dbName = "Orders"
$collectionName = "orders"
Add-Type -Path "$($mongoDbDriverPath)\MongoDB.Bson.dll"
Add-Type -Path "$($mongoDbDriverPath)\MongoDB.Driver.dll"
$db =[MongoDB.Driver.MongoDatabase]::Create("mongodb://localhost:27017/$($dbName)")
$collection = $db[$collectionName]

$query = [MongoDB.Driver.Builders.Query]::EQ("createdAt","2016-01-15T17:29:09.342Z")

$results = $collection.find($query)

在 MongoDB .NET Driver api 中,我无法进行复杂的查询,或者至少不知道如何进行。我可以根据一个特定的列进行查询,但不能进行复杂的查询,并且不能限制某些字段的输出。

有知道的请指教。注意:它不是一个 .Net 项目,它只是使用 mongoDB .net 驱动程序,但在 Powershell 中执行。

最佳答案

请在下面找到解决方案:它是一种在 powershell 脚本和最新的 mongo 驱动程序 (2.2.3) 中使用 c# 的灵活代码 - 因此您可以根据需要使用 c# 代码:-)

$mongoDbDriverPath = "C:\work\mongo"
$dbName = "deser"
$collectionName = "Foo"
$Assem = ( "$($mongoDbDriverPath)\MongoDB.Bson.dll", "$($mongoDbDriverPath)\MongoDB.Driver.dll","$($mongoDbDriverPath)\MongoDB.Driver.Core.dll")

$Source = @”
namespace profesor79
{
using System.Collections.Generic;

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

public static class Executor
{
public static List<Foo> GetData()
{
var connectionString = "mongodb://localhost:27017";
var _client = new MongoClient(connectionString);
var _database = _client.GetDatabase("deser");
var cole = _database.GetCollection<Foo>("Foo");
cole.InsertOne(new Foo());

var data = cole.Find<Foo>((new BsonDocument())).ToList();
return data;
}

public class Foo
{
public ObjectId Id { get; set; }
[BsonDictionaryOptions]
public Dictionary<string, string> Bar = new Dictionary<string, string>() { { "1", "text" }, { "2", "text" } };

}
}
}


"@

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp

[profesor79.Executor]::GetData()

看截图:

enter image description here

关于mongodb - 如何使用 Powershell 对 MongoDB 进行复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com