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

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

本文介绍了如何使用Powershell进行复杂查询MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to retrieve data from mongoDB using Powershell.Let's say I have db.orders collection and need to retrieve only orders created during last week and retrieve only specific columns for instance _id, status, createdAt fields.

订单收集模式

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

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

I can query it in mongo shell like this

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 ..而不是日期范围

But I need to do it in Powershell, here is my Powershell script with simple query which extract exactly createdAt date.. not range of dates

$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驱动程序api中,我无法进行复杂的查询,或者至少不知道如何进行查询.我可以根据一列特定的列进行查询,但不能构成一列复杂的列,并且不能限制某些字段的输出.

In MongoDB .NET Driver api, I can't make complex query or at least don't know how.I can query according to one specific column, but not making complex one and can't limit output for some fields.

请告知是否有人知道该怎么做.注意:这不是一个.Net项目,它仅使用mongoDB .net驱动程序,而是在Powershell中执行.

Please advise if anyone knows how to.Note: it's not a .Net project, it just uses mongoDB .net driver, but executed in Powershell.

推荐答案

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

please find solution below:It is a flexible code using c# inside powershell script and latest mongo drivers (2.2.3) - so you can play with c# code as required :-)

$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()

查看屏幕截图:

这篇关于如何使用Powershell进行复杂查询MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:15